My Solution 1:

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<>((a,b)-> a.val-b.val);
        for(ListNode node:lists){
            while(node!=null){
                queue.offer(node);
                node = node.next;
            }
            
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        while(!queue.isEmpty())
        {
            head.next = queue.poll();
            head=head.next;
        }
        head.next=null;
        return dummy.next;
    }
}

My Solution 2:

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<>((a,b)-> a.val-b.val);
        for(ListNode node:lists){
            if(node!=null)
                queue.offer(node);
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode head = dummy;
        while(!queue.isEmpty())
        {
            ListNode node = queue.poll();
            head.next = node;
            head=head.next;
            node=node.next;
            if(node!=null)
                queue.offer(node);
        }
        head.next=null;
        return dummy.next;
    }
}

 

posted on 2022-04-09 06:11  阳光明媚的菲越  阅读(9)  评论(0编辑  收藏  举报