Const
Definition for singly-linked list. class ListNode { val: number next: ListNode | null constructor(val?: number, next?: ListNode | null) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } }
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
// 暴力解法
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
if (lists.length === 0) {
return null;
}
let dummy = new ListNode(-1, null);
let tail = dummy;
let head1 = dummy.next;
for (let i = 0; i < lists.length; i++) {
let head2 = lists[i];
tail = dummy;
head1 = dummy.next;
while (head1 && head2) {
if (head1.val < head2.val) {
tail.next = head1;
tail = tail.next;
head1 = head1.next;
}
else {
tail.next = head2;
tail = tail.next;
head2 = head2.next;
}
}
while (head1) {
tail.next = head1;
tail = tail.next;
head1 = head1.next;
}
while (head2) {
tail.next = head2;
tail = tail.next;
head2 = head2.next;
}
}
return dummy.next;
};
23.合并K个升序链表
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:
lists = [[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