题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类一维数组
* @return ListNode类
*/
function hb(p1,p2){
let head={
val:null,
next:null
}
let cur=head;
while(p1&&p2){
if(p1.val<=p2.val){
cur.next=p1
cur=cur.next
p1=p1.next
}else{
cur.next=p2
cur=cur.next
p2=p2.next
}
}
if(p1) cur.next=p1
else cur.next=p2
return head.next
}
function mergeKLists( lists ) {
// write code here
for(let i=1;i<lists.length;i++){
let p3=hb(lists[0],lists[i])
lists[0]=p3
}
return lists[0]
}
module.exports = {
mergeKLists : mergeKLists
};
查看11道真题和解析
