Skip to content

Commit bdba92d

Browse files
committed
Add Merge Two Sorted Lists solution
1 parent f92dbb5 commit bdba92d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* [Problem]: [21] Merge Two Sorted Lists
3+
*
4+
* (https://leetcode.com/problems/merge-two-sorted-lists/description/)
5+
*/
6+
7+
class ListNode {
8+
val: number;
9+
next: ListNode | null;
10+
constructor(val?: number, next?: ListNode | null) {
11+
this.val = val === undefined ? 0 : val;
12+
this.next = next === undefined ? null : next;
13+
}
14+
}
15+
16+
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
17+
//시간복잡도 O(m+n)
18+
//공간복잡도 O(1)
19+
function loopFunc(list1: ListNode | null, list2: ListNode | null): ListNode | null {
20+
let current: ListNode = new ListNode();
21+
let dummy = current;
22+
23+
while (list1 !== null && list2 !== null) {
24+
if (list1.val < list2.val) {
25+
current.next = list1;
26+
list1 = list1.next;
27+
} else {
28+
current.next = list2;
29+
list2 = list2.next;
30+
}
31+
32+
current = current.next;
33+
}
34+
35+
current.next = list1 !== null ? list1 : list2;
36+
37+
return dummy.next;
38+
}
39+
40+
//시간복잡도 O(m+n)
41+
//공간복잡도 O(m+n)
42+
function recursionFunc(list1: ListNode | null, list2: ListNode | null): ListNode | null {
43+
if (list1 === null) return list2;
44+
if (list2 === null) return list1;
45+
46+
if (list1.val < list2.val) {
47+
list1.next = recursionFunc(list1.next, list2);
48+
return list1;
49+
} else {
50+
list2.next = recursionFunc(list1, list2.next);
51+
return list2;
52+
}
53+
}
54+
55+
return recursionFunc(list1, list2);
56+
}

0 commit comments

Comments
 (0)