将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路就是,首先两个链表大头节点,谁小谁为返回链表的头。定义一个dummy节点作为返回值。剩下的谁小就往新链表里放就完事了。别忘了最后把剩余的节点放进去就行。
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) return list2;
if (!list2) return list1;
ListNode* cur;
if (list1->val <= list2->val) {
cur = list1;
list1 = list1->next;
}
else {
cur = list2;
list2 = list2->next;
}
ListNode* dummy = cur;
while (list1 && list2) {
if (list1->val <= list2->val) {
cur->next = list1;
cur = cur->next;
list1 = list1->next;
}
else {
cur->next = list2;
cur = cur->next;
list2 = list2->next;
}
}
while (list1) {
cur->next = list1;
cur = cur->next;
list1 = list1->next;
}
while (list2) {
cur->next = list2;
cur = cur->next;
list2 = list2->next;
}
return dummy;
}
};
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 not list1:
return list2
if not list2:
return list1
if list1.val <= list2.val:
cur = list1
list1 = list1.next
else:
cur = list2
list2 = list2.next
dummy = cur
while list1 and list2:
if list1.val <= list2.val:
cur.next = list1
cur = cur.next
list1 = list1.next
else:
cur.next = list2
cur = cur.next
list2 = list2.next
while list1:
cur.next = list1
cur = cur.next
list1 = list1.next
while list2:
cur.next = list2
cur = cur.next
list2 = list2.next
return dummy
递归也能做,代码更简单,但是不好想。男人何苦为难自己。