forked from xiaoyu2er/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
023-Merge-k-Sorted-Lists.js
84 lines (75 loc) · 1.37 KB
/
023-Merge-k-Sorted-Lists.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/**
* https://leetcode.com/problems/merge-k-sorted-lists/description/
* Difficulty:Hard
*
* 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) {
return lists.reduce((a, b) => merge2lists(a, b), null)
};
function merge2lists(a, b) {
if (!a && !b) return null;
if (!a) return b;
if (!b) return a;
var h;
if (a.val < b.val) {
h = a;
a = a.next;
} else {
h = b;
b = b.next;
}
var t = h;
while (a && b) {
if (a.val < b.val) {
t.next = a;
t = t.next;
a = a.next;
} else {
t.next = b;
t = t.next;
b = b.next;
}
}
if (a) t.next = a;
if (b) t.next = b;
return h;
}
var a = {
val: 1,
next: {
val: 4,
next: {
val: 7,
next: null
}
}
}
var b = {
val: 2,
next: {
val: 8,
next: {
val: 9,
next: null
}
}
}
var c = {
val: 3,
next: {
val: 10,
next: null
}
}
// console.log(merge2lists(a, b));
console.log(mergeKLists([a, b, c]))