leetcode23. 合并K个升序链表

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

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

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

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

 public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> Nodes_set= new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                if(o1.val<o2.val)
                    return 1;
                if(o1.val>o2.val)
                    return -1;
                else
                    return 0;
            }
        });
        ListNode head= new ListNode();
        ListNode cur=head;
        for(ListNode node_list : lists)
        {
            ListNode t=node_list;
            while (t!=null)
            {
                Nodes_set.add(t);
                t=t.next;
            }
        }
        while (!Nodes_set.isEmpty())
        {
            cur.next=Nodes_set.poll();
            cur=cur.next;
            cur.next=null;//在拿出来之后以一定要和原来的链断开连接,否则
        }
        return head.next;

    }
posted @ 2021-08-04 10:46  LiangLiangAA  阅读(20)  评论(0编辑  收藏  举报
theme: { name: 'geek', avatar: '', headerBackground: '' // ... },