Skip to content

Commit 904acd5

Browse files
committed
merge-two-sorted-lists solution
1 parent b5a8f86 commit 904acd5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
/**
11+
* @param linked_list list1
12+
* @param linked_list list2
13+
* @returns 정렬된 linked_list
14+
* @description
15+
* - 연결리스트로 각 단계를 탐색하려니 접근 방법이 떠오르지 않음
16+
* - 해당 유형의 문제를 더 풀어볼 예정
17+
*/
18+
19+
function mergeTwoLists(
20+
list1: ListNode | null,
21+
list2: ListNode | null
22+
): ListNode | null {
23+
if (!list1 && !list2) {
24+
return null;
25+
}
26+
27+
const temp = new ListNode();
28+
let current = temp;
29+
30+
while (list1 && list2) {
31+
if (list1.val < list2.val) {
32+
current.next = list1;
33+
list1 = list1.next;
34+
} else {
35+
current.next = list2;
36+
list2 = list2.next;
37+
}
38+
current = current.next;
39+
}
40+
current.next = list1 || list2;
41+
42+
return temp.next;
43+
}
44+
45+
const list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
46+
const list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
47+
48+
mergeTwoLists(list1, list2);
49+

0 commit comments

Comments
 (0)