BM5 合并k个已排序的链表

题目描述

合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。

思路分析

之前已经完成了两条有序链表的排序,那么对于任意条有序链表的合并我们都可以借助之前的方法。
借助之前的函数,每次传递一条链表进去,最终返回出一条链表

代码参考

/* 借助于之前的合并两条有序链表的函数来完成,
  每次传递两条链表进去,当数组为空时则返回我们要的那条链表
*/
function mergeKLists (lists) {
  // write code here
  let nodes = new ListNode(-1)
  let p = mergeTwoList(nodes.next, lists.pop())
  while (lists.length > 0) {
    p = mergeTwoList(p, lists.pop())
  }
  return p
}
function mergeTwoList (pHead1, pHead2) {
  if (pHead1 === null) return pHead2
  if (pHead2 === null) return pHead1
  const node = new ListNode(-1)
  let pre = node
  while (pHead1 && pHead2) {
    if (pHead1.val <= pHead2.val) {
      pre.next = pHead1
      pHead1 = pHead1.next
    } else {
      pre.next = pHead2
      pHead2 = pHead2.next
    }
    pre = pre.next
  }
  pre.next = pHead1 === null ? pHead2 : pHead1
  return node.next
}
posted @ 2022-12-30 22:51  含若飞  阅读(35)  评论(0编辑  收藏  举报