I have been facing problems with this code for Merging K sorted Linked List for a long time.
https://leetcode.com/problems/merge-k-sorted-lists/description/
I'd appreciate it if someone can help me with the code.
ListNode definition:
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists==null || lists.length==0) return null;
PriorityQueue<ListNode> pq= new PriorityQueue<ListNode>(lists.length, (a,b)-> a.val-b.val);
ListNode head=new ListNode(-1);
ListNode tail=head;
for(ListNode node:lists){
if(node!=null)
pq.add(node);
}
while(!pq.isEmpty()){
tail.next=pq.poll();
tail=tail.next;
if(tail.next!=null){
pq.add(tail.next);
}
}
return head.next;
}
}
I am facing problem in the line: PriorityQueue<ListNode> pq= new PriorityQueue<ListNode>(lists.length, (a,b)-> a.val-b.val);
I am unable to understand why we even need this line. By default priority queue gives the highest priority to the smallest element. Why can't we simply add nodes and remove them later? Also, Why don't we need a comparator when we insert an integer?