2020年6月23日 星期二

LeetCode 21. Merge Two Sorted Lists [Easy] [C++] 解題筆記

這題給定兩個排序好的 Linked List,要我們將兩個 list 拼接成一個排序好的 list。

EX:
        Input: 1->2->4, 1->3->4
       Output: 1->1->2->3->4->4
想法:
    基本上就是 merge sort 的 merge 的概念,同時遍歷兩個 list ,每次將較小的 node 串接到新的 list 上,直到
其中一者為空,再把剩下不為空的 list 串接上去。

完整程式碼:
解法一(recursive):
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (l1 == NULL) {
            return l2;
        }
        if (l2 == NULL) {
            return l1;
        }       
        ListNode* head;
        if (l1->val < l2->val) {    
            head = l1;
            l1->next = mergeTwoLists(l1->next, l2);
        }
        else {
            head = l2;
            l2->next = mergeTwoLists(l1, l2->next);
        }
        return head;
    }
};
解法二(iterative):
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode *cur = &dummy;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            }
            else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = (l1)? l1 : l2;
        
        return dummy.next;
    }
};

沒有留言:

張貼留言