Typescript-Algorithms
    Preparing search index...

    Variable merge_k_sorted_listsConst

    merge_k_sorted_lists: (lists: (null | ListNode)[]) => null | ListNode = mergeKLists

    23.合并K个升序链表

    给你一个链表数组,每个链表都已经按升序排列。

    请你将所有链表合并到一个升序链表中,返回合并后的链表。


    输入: lists = [[1,4,5],[1,3,4],[2,6]]
    输出: [1,1,2,3,4,4,5,6]


    输入: lists = []
    输出: []


    输入: 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

    Type declaration

      • (lists: (null | ListNode)[]): null | ListNode
      • 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) } }

        Parameters

        • lists: (null | ListNode)[]

        Returns null | ListNode

    1. 两两合并,循环重置head1和tail
    2. 合并两个有序链表
    /**
    * 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;
    };