23. Merge k Sorted Lists

PriorityQueue data structure

/**
 * Definition for singly-linked list.
 * 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) {
        //PriorityQueue method:
        // queue.poll()
        // queue.add()
        // queue.isEmpty()
        // queue.peek()
        ListNode  head = new ListNode();
        ListNode result = head;
        if(lists.length==0) return result.next;
        PriorityQueue<ListNode> priorityQueue=new PriorityQueue<>(lists.length, (a,b)->a.val-b.val);
        for(ListNode node: lists){
            // null node is not legal
            if (node!=null){
               priorityQueue.add(node); 
            }
        }
        
        while(!priorityQueue.isEmpty()){
            ListNode topNode = priorityQueue.poll();
            head.next=topNode;
            head=head.next;
            if(topNode.next!=null){
                priorityQueue.add(topNode.next);
            }
        }
        return result.next;
    }
}

Last updated

Was this helpful?