23. Merge k Sorted Lists

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        }){};

        // init
        for (ListNode node : lists) {
            if (node != null) {
                queue.offer(node);
            }
        }

        // merge k sorted lists
        ListNode dummy = new ListNode(42);
        ListNode p = dummy;
        while (!queue.isEmpty()) {
            ListNode smallest = queue.poll();
            p.next = smallest;
            p = p.next;
            smallest = smallest.next;
            if (smallest != null) {
                queue.offer(smallest);
            }
        }
        return dummy.next;
    }
}