File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/merge-k-sorted-lists/description/
3+ * Definition for singly-linked list.
4+ * function ListNode(val, next) {
5+ * this.val = (val===undefined ? 0 : val)
6+ * this.next = (next===undefined ? null : next)
7+ * }
8+ */
9+ /**
10+ * @param {ListNode[] } lists
11+ * @return {ListNode }
12+ */
13+ var mergeKLists = function ( lists ) {
14+ if ( lists . length === 0 ) {
15+ return null ;
16+ }
17+
18+ while ( lists . length > 1 ) {
19+ const merged = [ ] ;
20+ const size = lists . length ;
21+
22+ for ( let i = 0 ; i < size ; i += 2 ) {
23+ const l1 = lists [ i ] ;
24+ const l2 = i + 1 < lists . length ? lists [ i + 1 ] : null ;
25+ merged . push ( mergeLists ( l1 , l2 ) ) ;
26+ }
27+
28+ lists = merged ;
29+ }
30+
31+ return lists [ 0 ] ;
32+ } ;
33+
34+ function mergeLists ( l1 , l2 ) {
35+ const head = new ListNode ( 0 ) ;
36+ let cur = head ;
37+ while ( l1 !== null && l2 !== null ) {
38+ if ( l1 . val < l2 . val ) {
39+ cur . next = l1 ;
40+ l1 = l1 . next ;
41+ } else {
42+ cur . next = l2 ;
43+ l2 = l2 . next ;
44+ }
45+ cur = cur . next ;
46+ }
47+ cur . next = l1 === null ? l2 : l1 ;
48+ return head . next ;
49+ }
You can’t perform that action at this time.
0 commit comments