Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 21. Merge Two Sorted Lists

Rain Hu

21. Merge Two Sorted Lists


一、題目

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a 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.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Iteration

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    ListNode* dummy = new ListNode(-1);     // 建一個虛假鏈表做為頭
    ListNode* curr = dummy;
    while (list1 && list2) {                // 依序將兩個表由小到大遍歷一遍
        if (list1->val <= list2->val) { 
            curr->next = list1;
            list1 = list1->next;
        } else {
            curr->next = list2;
            list2 = list2->next;
        }
        curr = curr->next;
    }
    if (list1) curr->next = list1;          // 將尚未遍歷完的鏈表接到尾巴
    if (list2) curr->next = list2;
    return dummy->next;                     // 最後記得回傳虛假鏈表的下一個節點
}

2. Recursion

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    if (!list1) return list2;               // 其中一者遍歷完,將剩下的鏈表接到尾巴
    if (!list2) return list1;
    ListNode* res;
    if (list1->val <= list2->val) {
        res = list1;
        list1->next = mergeTwoLists(list1->next , list2);   // 較小的鏈表前進一個節點
    } else {
        res = list2;
        list2->next = mergeTwoLists(list1, list2->next);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 22. Generate Parentheses
Next
[LeetCode] 1047. Remove All Adjacent Duplicates In String