题目链接
23. 合并 K 个升序链表 - 力扣(LeetCode)
题解:
-
首先特判------数组长度为0的 返回null ,长度为1的返回 lists[0]
-
对于这题,我们先首先记录,每个列表的第一个元素,维护这个数组,我们后续每次都从这个数组里面挑选最小值,来作为新链表的 下一个元素 ,如果当前下标的 数组被采用,则 往后走,链表往后走,无非就是先记录下一个的值,然后替换掉 我们维护的数组 当前位置的元素。
-
需要特别判断 数组元素为null的情况(其实也可以在 第一次就预处理了)
-
用一个循环来 不停找最小值,对于出现每一次null的情况,我们用count计数,出现一次null的情况,count--,代表这个链表已经走完,直到count为0,说明循环该结束了,返回答案即可

代码:
javascript
// 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) {
if (lists.length === 0) return null
if (lists.length === 1) return lists[0]
let res = null
let curArr = [], count = lists.length, head = null
// 头节点
for (let i = 0; i < lists.length; i++) {
curArr.push(lists[i])
}
function getMin(nodes) {
let min = Number.MAX_SAFE_INTEGER, nodePos = 0
for (let i = 0; i < nodes.length; i++) {
// console.log(nodes[i].val)
if (nodes[i] && min > nodes[i].val) {
nodePos = i
min = nodes[i].val
}
}
return nodePos
}
while (count) {
let pos = getMin(curArr)
if (curArr[pos] === null) {
count--
continue
}
if (res === null) head = res = curArr[pos]
else {
res.next = curArr[pos]
res = curArr[pos]
}
let t = res.next
res.next = null
if (t !== null) curArr[pos] = t
else {
count--
curArr[pos] = null
}
}
return head
};