/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
var n = lists.length;
if (n == 0) {
return null;
}
if (n == 1) {
return lists[0];
}
var newLists = [];
for (var i = 0; i < n - 1 ; i += 2) {
newLists.push(mergeTwoLists(lists[i], lists[i+1]));
}
if (lists.length % 2 == 1) {
newLists.push(lists[n-1]);
}
return mergeKLists(newLists);
};
function mergeTwoLists(list1, list2) {
var mergedList = new ListNode(null, null);
var pointer1 = list1, pointer2 = list2, pointer3 = mergedList;
while (pointer1 !== null && pointer2 !== null) {
var value;
if (pointer1.val < pointer2.val) {
value = pointer1.val;
pointer1 = pointer1.next;
} else {
value = pointer2.val;
pointer2 = pointer2.next;
}
pointer3.next = new ListNode(value, null);
pointer3 = pointer3.next;
}
while (pointer1 !== null) {
pointer3.next = new ListNode(pointer1.val, null);
pointer3 = pointer3.next;
pointer1 = pointer1.next;
}
while (pointer2 !== null) {
pointer3.next = new ListNode(pointer2.val, null);
pointer3 = pointer3.next;
pointer2 = pointer2.next;
}
return mergedList.next;
};
No comments:
Post a Comment