21. 合并两个有序链表 - 力扣(LeetCode)https://leetcode.cn/problems/merge-two-sorted-lists/description/?envType=study-plan-v2&envId=top-100-liked
常规法
创建一个新链表,遍历list1与list2,将新链表指向list1与list2中更小的那个直至结束。
//c++
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {if(list1==nullptr||list2==nullptr) return list1?list1:list2;ListNode* ans=new ListNode(-1);ListNode* aa=ans;while(list1 && list2){if(list1->val<=list2->val){aa->next=list1;list1=list1->next;}else{aa->next=list2;list2=list2->next;}aa=aa->next;}aa->next=list1?list1:list2;return ans->next;}
};#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:if list1==None or list2==None:return list1 if list1 else list2ans=ListNode()aa=answhile list1 and list2:if list1.val<=list2.val:aa.next=list1list1=list1.nextelse:aa.next=list2list2=list2.nextaa=aa.nextaa.next=list1 if list1 else list2return ans.next
递归法
进入递归,哪个值更小,就使更小值指向进入对应链表的下一个指针的递归并返回。
//c++
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {if(list1==nullptr) return list2;else if(list2==nullptr) return list1;else if(list1->val<=list2->val){list1->next=mergeTwoLists(list1->next,list2);return list1;}else{list2->next=mergeTwoLists(list1,list2->next);return list2;}}
};#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:if list1 is None:return list2elif list2 is None:return list1elif list1.val<=list2.val:list1.next=self.mergeTwoLists(list1.next,list2)return list1else:list2.next=self.mergeTwoLists(list1,list2.next)return list2