其他分享
首页 > 其他分享> > 23. Merge k Sorted Lists

23. Merge k Sorted Lists

作者:互联网

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;
    }
}

 

标签:node,dummy,head,ListNode,Lists,next,queue,Merge,Sorted
来源: https://www.cnblogs.com/feiflytech/p/16120726.html