題目連結(https://leetcode.com/problems/merge-two-sorted-lists/description/)
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
list1
and list2
舉例用的兩個 linked list 大小不要相等,相等的話 trace code 時會比較難解釋。
Input: list1 = [1,3,5], list2 = [2,6]
Output: [1,2,3,5,6]
list1
and list2
list1->val
較小,此排序位即為 list1 中的數,將其放入新的 linked list,並從list1->next
當作新的引數繼續做遞迴。list1
and list2
非空時,如果list1->val
較大,將 tail 的下一位指向list1->val
,list1 前進一位,反之亦然。結束比較後,tail 往前一位。/**
* 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;
if(list1->val < list2->val){
list1->next = mergeTwoLists(list1->next, list2);
return list1;
} else{
list2->next = mergeTwoLists(list1, list2->next);
return list2;
}
}
};
/**
* 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) {
ListNode dummy(0); //虛擬的頭
ListNode* tail = &dummy; //指向結果鏈表的尾部
while(list1 && list2){
if(list1->val <= list2->val){
tail->next = list1; // 將較小的節點連接到結果鏈表
list1 = list1->next; // 移動到下一個節點
}else{
tail->next = list2; // 將較小的節點連接到結果鏈表
list2 = list2->next; // 移動到下一個節點
}
tail = tail->next;
}
tail->next = list1 ? list1 : list2; //list1非空 tail 則接回list1 ,空則接回list2
return dummy.next;
}
};
迭代步驟:
tail | list1 | list2 | 動作 |
---|---|---|---|
dummy | 1->3->5 | 2->6 | 1 < 2 → tail->next = 1, list1++ |
1 | 3->5 | 2->6 | 3 > 2 → tail->next = 2, list2++ |
2 | 3->5 | 6 | 3 < 6 → tail->next = 3, list1++ |
3 | 5 | 6 | 5 < 6 → tail->next = 5, list1++ |
5 | nullptr | 6 | list1空 → tail->next = list2 (6) |
return [1,2,3,5,6] |
tail->next = list1 ? list1 : list2;
三元運算子寫法,等價於:
if (list1 != nullptr) //list非空
tail->next = list1; //將tail接到list1
else
tail->next = list2;
ListNode dummy(0);
tail = tail->next;