1+ /*
2+ Merge k Sorted Lists
3+ https://leetcode.com/problems/merge-k-sorted-lists/
4+
5+ Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
6+
7+ Example:
8+
9+ Input:
10+ [
11+ 1->4->5,
12+ 1->3->4,
13+ 2->6
14+ ]
15+ Output: 1->1->2->3->4->4->5->6
16+ */
17+
18+ var ListNode = require ( '../utilsClasses/ListNode' ) . ListNode ;
19+
20+ var mergeKLists = function ( lists ) {
21+ if ( lists . length === 0 )
22+ return null ;
23+
24+ var queue = [ ] ;
25+ for ( var i = 0 ; i < lists . length ; i ++ )
26+ queue . push ( lists [ i ] ) ;
27+
28+ while ( queue . length > 1 ) {
29+ list1 = queue . shift ( ) ;
30+ list2 = queue . shift ( ) ;
31+ queue . push ( mergeLists ( list1 , list2 ) ) ;
32+ }
33+
34+ return queue . shift ( ) ;
35+ } ;
36+
37+ var mergeLists = function ( list1 , list2 ) {
38+ if ( list1 === null ) {
39+ return list2 ;
40+ } else if ( list2 === null )
41+ return list1 ;
42+
43+ var iter1 = list1 ;
44+ var iter2 = list2 ;
45+ var head ;
46+
47+ if ( iter1 . val < iter2 . val ) {
48+ head = iter1 ;
49+ iter1 = iter1 . next
50+ } else {
51+ head = iter2 ;
52+ iter2 = iter2 . next ;
53+ }
54+
55+ var iterHead = head ;
56+ while ( iter1 !== null && iter2 !== null ) {
57+ if ( iter1 . val < iter2 . val ) {
58+ iterHead . next = iter1 ;
59+ iter1 = iter1 . next ;
60+ } else {
61+ iterHead . next = iter2 ;
62+ iter2 = iter2 . next ;
63+ }
64+ iterHead = iterHead . next ;
65+ iterHead . next = null ;
66+ }
67+
68+ if ( iter1 !== null ) {
69+ iterHead . next = iter1 ;
70+ } else if ( iter2 !== null ) {
71+ iterHead . next = iter2 ;
72+ }
73+
74+ return head ;
75+ }
76+
77+ var main = function ( ) {
78+ console . log ( mergeKLists ( [ ] ) ) ;
79+ console . log ( mergeKLists (
80+ [ null ]
81+ ) ) ;
82+ console . log ( mergeKLists (
83+ [ null , null ]
84+ ) ) ;
85+
86+ var list1 = ListNode . linkenList ( [ 1 , 2 , 3 ] ) ;
87+ var list2 = ListNode . linkenList ( [ 2 , 3 , 4 ] ) ;
88+ var list3 = ListNode . linkenList ( [ 5 , 6 ] ) ;
89+ var list4 = ListNode . linkenList ( [ 1 , 5 ] ) ;
90+ console . log ( mergeKLists (
91+ [ list1 , list2 , list3 , list4 ]
92+ ) ) ;
93+ }
94+
95+ module . exports . main = main ;
0 commit comments