File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments