class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
// adding all the starting element from each list to PQ
for (int i = 0; i < lists.length; i++) {
if (lists[i] != null) {
pq.add(lists[i]);
}
}
// Main work
if (pq.peek() != null) {
ListNode ans = new ListNode(0);
ListNode ansPointer = ans;
while (pq.size() != 0) {
ListNode t = pq.poll();
ansPointer.next = t;
ansPointer = ansPointer.next;
if (t.next != null) {
pq.add(t.next);
}
}
return ans.next;
} else {
return null;
}
}
}