天天看點

#yyds幹貨盤點# leetcode算法題:合并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 = [[]]

public ListNode mergeTwoLists(ListNode a, ListNode b) {
    if (a == null || b == null) {
        return a != null ? a : b;
    }
    ListNode head = new ListNode(0);
    ListNode tail = head, aPtr = a, bPtr = b;
    while (aPtr != null && bPtr != null) {
        if (aPtr.val < bPtr.val) {
            tail.next = aPtr;
            aPtr = aPtr.next;
        } else {
            tail.next = bPtr;
            bPtr = bPtr.next;
        }
        tail = tail.next;
    }
    tail.next = (aPtr != null ? aPtr : bPtr);
    return head.next;
}      

繼續閱讀