-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path023.js
More file actions
37 lines (35 loc) · 769 Bytes
/
023.js
File metadata and controls
37 lines (35 loc) · 769 Bytes
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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
const mergedArray = [];
for (let i = 0; i < lists.length; ++i) {
let list = lists[i];
while(list) {
mergedArray.push(list.val);
list = list.next;
}
}
mergedArray.sort((a, b) => a - b);
let mergedList = null;
let current = null;
mergedArray.forEach(function(value){
if (mergedList === null) {
mergedList = new ListNode(value);
current = mergedList;
} else {
var newNode = new ListNode(value);
current.next = newNode;
current = newNode;
}
})
return mergedList;
};