> For the complete documentation index, see [llms.txt](https://nataliekung.gitbook.io/solutions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nataliekung.gitbook.io/solutions/merge_k_sorted_lists/priority_queue.md).

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

}
