Skip to content

Commit d2800d8

Browse files
committed
feat(soobing): week10 > merge-k-sorted-lists
1 parent 0424c1b commit d2800d8

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

merge-k-sorted-lists/soobing.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 문제 설명
3+
* - k개의 정렬된 링크드 리스트 병합하기
4+
*
5+
* 아이디어
6+
* 1) 병합정렬 -> 대표적인 분할 정복(Divide and Conquer) 문제
7+
* - 두 리스트를 병합할 수 있는 함수를 계속해서 적용한다.
8+
* - 두 링크드 리스트 병합하는 예제
9+
* ㄴ @link https://leetcode.com/problems/merge-two-sorted-lists/description/
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+
class ListNode {
25+
val: number;
26+
next: ListNode | null;
27+
constructor(val?: number, next?: ListNode | null) {
28+
this.val = val === undefined ? 0 : val;
29+
this.next = next === undefined ? null : next;
30+
}
31+
}
32+
33+
function mergeList(list1: ListNode | null, list2: ListNode | null) {
34+
const dummy = new ListNode(0);
35+
let current = dummy;
36+
37+
while (list1 && list2) {
38+
if (list1.val <= list2.val) {
39+
current.next = list1;
40+
list1 = list1.next;
41+
} else {
42+
current.next = list2;
43+
list2 = list2.next;
44+
}
45+
current = current.next;
46+
}
47+
current.next = list1 || list2;
48+
49+
return dummy.next;
50+
}
51+
52+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
53+
return lists.reduce((acc, current) => {
54+
return mergeList(acc, current);
55+
}, null);
56+
}

0 commit comments

Comments
 (0)