Skip to content

Commit d58e437

Browse files
committed
#224 merge-two-sorted-lists solution
1 parent d684b59 commit d58e437

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

merge-two-sorted-lists/sungjinwi.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
풀이 :
3+
dummy를 맨 앞에 세우고 list1과 list2의 맨 앞 성분 value를 비교하며 dummy 뒤에 노드를 이어줌
4+
이어준 list는 next로 전진시키면서 계속 반복문
5+
둘 중 하나가 null이 되면 남은 리스트 전체를 맨 뒤에 이어줌
6+
7+
리스트 길이 : M, N
8+
9+
TC : O(M + N)
10+
번갈아서 나올 경우 두 리스트 전체의 길이에 비례
11+
12+
SC : O(1)
13+
기존 노드를 활용하므로 추가적인 메모리는 dummy와 tmp만 사용한다
14+
*/
15+
16+
/**
17+
* Definition for singly-linked list.
18+
* struct ListNode {
19+
* int val;
20+
* ListNode *next;
21+
* ListNode() : val(0), next(nullptr) {}
22+
* ListNode(int x) : val(x), next(nullptr) {}
23+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
24+
* };
25+
*/
26+
class Solution {
27+
public:
28+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
29+
ListNode dummy;
30+
ListNode *tmp;
31+
32+
tmp = &dummy;
33+
while (list1 && list2)
34+
{
35+
if (list1->val <= list2->val)
36+
{
37+
tmp->next = list1;
38+
list1 = list1->next;
39+
}
40+
else
41+
{
42+
tmp->next = list2;
43+
list2 = list2->next;
44+
}
45+
tmp = tmp->next;
46+
}
47+
if (list1)
48+
tmp->next = list1;
49+
else
50+
tmp->next = list2;
51+
return dummy.next;
52+
}
53+
};

0 commit comments

Comments
 (0)