Skip to content

Commit dc88ca3

Browse files
committed
21. Merge Two Sorted Lists
1 parent 03ded85 commit dc88ca3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Runtime: 0ms, Memory: 52.30MB
3+
*
4+
* 접근
5+
* 핵심은 두 리스트를 비교하면서 작은 값부터 정렬되도록 리스트를 만드는 것이다.
6+
* 두 연결 리스트 중 하나가 null이 될 때까지 현재 노드 값을 비교하여 더 작은 값을 새로운 리스트트 추가하고, 남은 리스트를 추가한다.
7+
*
8+
* 평소 접하는 배열이 아닌 링크드 리스트로 풀어야 했기에 접근 방식이 와닿지 않았다.
9+
* 처음에는 list1, list2가 하나의 노드라고 생각하여 헷갈렸지만, 실제로는 각 노드가 next를 통해 연결된 연결 리스트임이 중요하다.
10+
*/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* class ListNode {
15+
* val: number
16+
* next: ListNode | null
17+
* constructor(val?: number, next?: ListNode | null) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.next = (next===undefined ? null : next)
20+
* }
21+
* }
22+
*/
23+
24+
function mergeTwoLists(
25+
list1: ListNode | null,
26+
list2: ListNode | null
27+
): ListNode | null {
28+
let dummy = new ListNode(-1);
29+
let current = dummy;
30+
31+
while (list1 !== null && list2 !== null) {
32+
if (list1.val < list2.val) {
33+
current.next = list1;
34+
list1 = list1.next;
35+
} else {
36+
current.next = list2;
37+
list2 = list2.next;
38+
}
39+
current = current.next;
40+
}
41+
42+
current.next = list1 || list2;
43+
44+
return dummy.next;
45+
}

0 commit comments

Comments
 (0)