Skip to content

Commit e5fa42a

Browse files
committed
23 Merge k Sorted List solution
1 parent 19eb2e9 commit e5fa42a

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

typescript/23-Merge-k-Sorted-Lists.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
14+
if (lists.length === 0) return null
15+
16+
while (lists.length > 1) {
17+
let resultList = []
18+
19+
for (let i = 0; i < lists.length; i += 2) {
20+
let list1 = lists[i]
21+
let list2
22+
if (i + 1 > lists.length) list2 = null
23+
else list2 = lists[i + 1]
24+
resultList.push(mergeList(list1, list2))
25+
}
26+
27+
lists = resultList
28+
}
29+
return lists[0] || null
30+
}
31+
32+
function mergeList(
33+
list1: ListNode | null,
34+
list2: ListNode | null
35+
): ListNode | null {
36+
let dummyNode: ListNode | null = new ListNode()
37+
let tail = dummyNode
38+
39+
while (list1 && list2) {
40+
if (list1.val < list2.val) {
41+
tail.next = list1
42+
list1 = list1.next
43+
} else {
44+
tail.next = list2
45+
list2 = list2.next
46+
}
47+
tail = tail.next
48+
}
49+
tail.next = list1 || list2
50+
51+
return dummyNode.next
52+
}

0 commit comments

Comments
 (0)