Skip to content
On this page

23. 合并 K 个升序链表

给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 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 = [[]]
输出:[]

提示:
k == lists.length
0 <= k <= 10^4
0 <= lists[i].length <= 500
-10^4 <= lists[i][j] <= 10^4
lists[i] 按 升序 排列
lists[i].length 的总和不超过 10^4

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 new ListNode()
  let prevList = lists[0]
  for (let i = 1; i < lists.length; i++) {
    prevList = mergeTwoLists(prevList, lists[i])
  }
  return prevList
}

var mergeTwoLists = function (list1, list2) {
  var Head = new ListNode(),
    cur = Head
  while (list1 && list2) {
    if (list1.val < list2.val) {
      cur.next = list1
      cur = cur.next
      list1 = list1.next
    } else {
      cur.next = list2
      cur = cur.next
      list2 = list2.next
    }
  }
  if (list1) {
    cur.next = list1
  }
  if (list2) {
    cur.next = list2
  }
  return Head.next
}

// test
function ListNode(val, next) {
  this.val = val === undefined ? 0 : val
  this.next = next === undefined ? null : next
}

var l1 = new ListNode(1)
var lstNode1 = new ListNode(4)
var lstNode2 = new ListNode(5)
l1.next = lstNode1
lstNode1.next = lstNode2

var l2 = new ListNode(1)
var lstNode3 = new ListNode(3)
var lstNode4 = new ListNode(4)
l2.next = lstNode3
lstNode3.next = lstNode4

var l3 = new ListNode(2)
var lstNode5 = new ListNode(6)
l3.next = lstNode5

console.log(mergeKLists([l1,l2,l3]))