Skip to content

Commit 59e8a48

Browse files
committed
feat: Upload merge-two-sorted-lists (typescript)
1 parent 09cb2fa commit 59e8a48

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

merge-two-sorted-lists/mike2ox.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* source: https://leetcode.com/problems/merge-two-sorted-lists/
3+
* 풀이방법: 두 리스트를 비교하면서 작은 값을 결과 리스트에 추가
4+
*
5+
* 시간복잡도: O(n + m) (n: list1의 길이, m: list2의 길이)
6+
* 공간복잡도: O(1) (상수 공간만 사용)
7+
*
8+
*/
9+
10+
class ListNode {
11+
val: number;
12+
next: ListNode | null;
13+
constructor(val?: number, next?: ListNode | null) {
14+
this.val = val === undefined ? 0 : val;
15+
this.next = next === undefined ? null : next;
16+
}
17+
}
18+
19+
function mergeTwoLists(
20+
list1: ListNode | null,
21+
list2: ListNode | null
22+
): ListNode | null {
23+
const result = new ListNode();
24+
let current = result;
25+
while (list1 !== null && list2 !== null) {
26+
if (list1.val <= list2.val) {
27+
current.next = list1;
28+
list1 = list1.next;
29+
current = current.next;
30+
} else {
31+
current.next = list2;
32+
list2 = list2.next;
33+
current = current.next;
34+
}
35+
}
36+
if (list1 !== null) {
37+
current.next = list1;
38+
}
39+
if (list2 !== null) {
40+
current.next = list2;
41+
}
42+
return result.next; // 처음에 추가한 더미 노드 제외
43+
}

0 commit comments

Comments
 (0)