1. 程式人生 > >21. Merge Two Sorted Lists 解法

21. Merge Two Sorted Lists 解法

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

可新建一個連結串列,比較兩個連結串列中的元素值,把較小的那個鏈到新連結串列中,由於兩個輸入連結串列的長度可能不同,所以最終會有一個連結串列先完成插入所有元素,則直接另一個未完成的連結串列直接鏈入新連結串列的末尾。程式碼如下:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *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;
    }
};