0

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?

Chaosfire
  • 4,818
  • 4
  • 8
  • 23
  • 2
    Please share definition of `ListNode`. Most probably it does not implement [Comparable](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Comparable.html) and custom comparator is needed. The constructor in question is explained in the [docs](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/PriorityQueue.html#%3Cinit%3E(int,java.util.Comparator)). – Chaosfire Apr 25 '23 at 16:28
  • 2
    This question should help - [How do I use a PriorityQueue?](https://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue). Also, you are not inserting an integer, you insert a `ListNode`, since your queue is declared to contain nodes - `PriorityQueue pq = ...`. – Chaosfire Apr 25 '23 at 16:49
  • Thanks! This link helped me in clearing all my doubts – Naina Mathur Apr 25 '23 at 17:43
  • 1
    BTW it is recommended not to use `a.val-b.val` - subtraction can overflow/underflow - better use `Integer.compare()` – user16320675 Apr 25 '23 at 19:00

0 Answers0