Priority queue

public ListNode mergeKLists(ListNode[] lists) {

if(lists==null || lists.length==0) return null;

PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length,

new Comparator<ListNode>() {

public int compare(ListNode a, ListNode b) {

if (a.val > b.val)

return 1;

else if(a.val == b.val)

return 0;

else

return -1;

}

});

for(ListNode l:lists){

if(l!=null)

pq.offer(l);

}

ListNode head= new ListNode(0);

ListNode node,p=head;

while(!pq.isEmpty()){

node=pq.poll();

if(node.next!=null){

pq.offer(node.next);

}

p.next=node;

p=p.next;

}

return head.next;

}

Last updated

Was this helpful?