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

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

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode() {}
    7. * ListNode(int val) { this.val = val; }
    8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    9. * }
    10. */
    11. class Solution {
    12. public ListNode mergeKLists(ListNode[] lists) {
    13. Queue<ListNode> q = new PriorityQueue<>((v1, v2) -> v1.val - v2.val);
    14. for (ListNode node : lists) {
    15. if(node != null) {
    16. q.offer(node);
    17. }
    18. }
    19. ListNode dummyHead = new ListNode(-1);
    20. ListNode tail = dummyHead;
    21. while (!q.isEmpty()) {
    22. ListNode minValue = q.poll();
    23. tail.next = minValue;
    24. tail = tail.next;
    25. if (tail.next != null) {
    26. q.offer(tail.next);
    27. }
    28. }
    29. return dummyHead.next;
    30. }
    31. }

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
    image.png