Merge k Sorted Lists
Problem statement
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Example 1:
Input: lists = [[1,4,5],[1,3,4],[2,6]]Output: [1,1,2,3,4,4,5,6]Explanation: The linked-lists are:[ 1->4->5, 1->3->4, 2->6]merging them into one sorted list:1->1->2->3->4->4->5->6
Example 2:
Input: lists = []Output: []
Example 3:
Input: lists = [[]]Output: []
Constraints:
k == lists.length0 <= k <= 1040 <= lists[i].length <= 500-104 <= lists[i][j] <= 104lists[i]is sorted in ascending order.- The sum of
lists[i].lengthwill not exceed104.
My solution
/**
* 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) {
function merge(left, right) {
const newNode = new ListNode();
let currentNode = newNode;
while(left && right) {
// console.log(left, right)
// console.log("currentNode", currentNode)
// console.log("left.val", left.val)
// console.log("right.val", right.val)
if (left.val < right.val) {
// console.log("LEFT ASSIGN")
currentNode.next = left;
left = left.next;
} else {
// console.log("RIGHT ASSIGN")
currentNode.next = right;
right = right.next
}
currentNode = currentNode.next;
}
if (left) {
currentNode.next = left;
} else if (right) {
currentNode.next = right;
}
// console.log("currentNode", currentNode.next)
return newNode.next;
}
let root = lists[0];
for (let i = 1; i < lists.length; i++) {
// console.log("=====")
root = merge(root, lists[i])
}
return root || null;
};