forked from dnshi/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeKSortedLists.js
54 lines (50 loc) · 1.27 KB
/
MergeKSortedLists.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Source : https://oj.leetcode.com/problems/merge-k-sorted-lists/
// Author : Dean Shi
// Date : 2015-06-12
/**********************************************************************************
*
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
var i, tmp;
while (lists.length >= 2) {
tmp = [];
for (i = lists.length - 1; i > 0; i -= 2) {
tmp.push(mergeTwoLists(lists[i], lists[i - 1]));
}
if (i === 0) {
tmp.push(lists[0]);
}
lists = tmp;
}
return lists[0] || [];
};
function mergeTwoLists(l1, l2) {
var result, node;
result = node = new ListNode();
while (l1 && l2) {
if (l1.val > l2.val) {
node.next = l2;
l2 = l2.next;
} else {
node.next = l1;
l1 = l1.next;
}
node = node.next;
}
node.next = l1 ? l1 : l2;
return result.next;
}