给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]] 输出:[1,1,2,3,4,4,5,6] 解释:链表数组如下: [ 1->4->5, 1->3->4, 2->6 ] 将它们合并到一个有序链表中得到。 1->1->2->3->4->4->5->6
示例 2:
输入:lists = [] 输出:[]
示例 3:
输入:lists = [[]] 输出:[]
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
// function ListNode(val, next) {
// this.val = (val === undefined ? 0 : val)
// this.next = (next === undefined ? null : next)
// }
var mergeKLists = function (lists) {
if(lists.length==1) return lists[0]
let head = new ListNode(null, null)
let res = head
let l1 = lists[0]
for (let i = 1; i < lists.length; i++) {
let l2 = lists[i]
while (l2 != null && l1 != null) {
if (l1.val <= l2.val) {
head.next = l1
head = head.next
l1 = l1.next
} else {
head.next = l2
head = head.next
l2 = l2.next
}
}
if (l1 == null) {
head.next = l2
}
if (l2 == null) {
head.next = l1
}
l1 = res.next
head = res
}
return res.next
};
考虑两两合并链表