(Leetcode) [Linked List] Merge two sorted lists

Topic: Linked List
Difficulty: Easy

Question

Given the heads of two sorted linked lists, merge them in a one sorted list by splicing together their nodes.


Solution

์‚ฝ์งˆ์„ ์—„์ฒญ๋‚˜๊ฒŒ ํ–ˆ๋‹ค. ์“ธ ๋ฐ ์—†์ด ์‹œ๊ฐ„์„ ๋„ˆ๋ฌด ๋บ์–ด๋จน์—ˆ๋‹ค.
๊ทธ๋ƒฅ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ž„์˜์˜ node๋ฅผ ํ•˜๋‚˜ ํ˜•์„ฑํ•˜๊ณ , ๊ทธ ๋’ค๋กœ ์ˆœ์„œ๋Œ€๋กœ list์—์„œ node๋ฅผ ๋นผ๋‚ด์™€์„œ ์ด์–ด ๋ถ™์—ฌ์„œ tempNode.next๋ฅผ returnํ•˜๋ฉด ๋๋‹ค. ํ•˜์ง€๋งŒ ๋‚œ ์ž˜๋ชป ์ดํ•ดํ•˜๊ณ  ์ž„์˜์˜ ๋…ธ๋“œ๋ฅผ ํ˜•์„ฑํ•˜๋ฉด ์•ˆ ๋˜๊ณ  ๋ฌด์กฐ๊ฑด list1์ด๋‚˜ list2 ๋’ค์— ์ด์–ด ๋ถ™์—ฌ์„œ return ํ•ด์•ผํ•˜๋Š”์ค„ ์•Œ์•˜๋‹ค.

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) {}
};

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    if (!list1 && !list2) { return nullptr; }
    if (!list1) { return list2; }
    if (!list2) { return list1; }

    // temporary node to hang the result on
    ListNode dummy;

    // tail points to the last result node
    ListNode* tail = &dummy;
    tail->next = nullptr;

    while (1) {
        ListNode* temp1 = list1;
        ListNode* temp2 = list2;
        if (list1 == nullptr) {
            tail->next = list2;
            break;
        }
        else if (list2 == nullptr) {
            tail->next = list1;
            break;
        }

        if (list1->val <= list2->val) {
            list1 = list1->next;
            tail->next = temp1;
            temp1->next = nullptr;
        }
        else {
            list2 = list2->next;
            tail->next = temp2;
            temp2->next = nullptr;
        }
        tail = tail->next;
    }

    return (dummy.next);
}


Alternate solution: Recursion

Merge two sorted linked list๋Š” recursion ์ฝ”๋“œ๋กœ ์“ฐ๊ธฐ ์•„์ฃผ ๊ฐ„๊ฒฐํ•œ ๋ฌธ์ œ์ด๋‹ค. ์ฒซ๋ฒˆ์งธ์— ์‚ฌ์šฉํ•œ iterative ๋ฐฉ๋ฒ•๋ณด๋‹ค ํ›จ์”ฌ ๊ฐ„๋‹จํ•˜๋‹ค.
๋Œ€์‹  runtime์€ ๋” ๊ฑธ๋ฆฐ๋‹ค.

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    ListNode* result = nullptr;

    if (list1 == nullptr)
        return list2;
    else if (list2 == nullptr)
        return list1;

    if (list1->val <= list2->val) {
        result = list1;
        result->next = mergeTwoLists(list1->next, list2);
    }
    else {
        result = list2;
        result->next = mergeTwoLists(list1, list2->next);
    }

    return result;
}

merge-two-sorted-lists-recursion.jpg

Summary

In order to merge two sorted lists, first create a dummy node, then extract the nodes from two lists according to their value and add them to the end (tail).
Recursion would be the another method. It provides more concise code.


Reference

https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/#:~:text=Write%20a%20SortedMerge()%20function,should%20return%20the%20new%20list.

Categories:

Updated:

Leave a comment