(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;
}
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.
Leave a comment