21. Merge Two Sorted Lists

  • Hardness: \(\color{green}\textsf{Easy}\)
  • Ralated Topics: Linked ListRecursion

一、題目

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:

  • Input: list1 = [1,2,4], list2 = [1,3,4]
  • Output: [1,1,2,3,4,4]

Example 2:

  • Input: list1 = [], list2 = []
  • Output: []

Example 3:

  • Input: list1 = [], list2 = [0]
  • Output: [0]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

二、分析

  • 這一題也是 linked list 的經典題型,特別需考慮到空鏈表的情況,所以可以用一個 dummy head 來避免這個情況的發生。

三、解題

1. Iteration

  • Time complexity: \(O(m+n)\)
  • Space complexity: \(O(1)\)
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

  • Time complexity: \(O(m+n)\)
  • Space complexity: \(O(1)\)
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