Merge k sorted lists

rt


public ListNode mergeKLists(List<ListNode> lists) {  
    // write your code here
    if (lists.size() == 0) return null;
    Queue<ListNode> pq = new PriorityQueue(10, new Comparator<ListNode>() {
        public int compare(ListNode n1, ListNode n2) {
            return n1.val - n2.val;// minHeap  
        }
    });
    ListNode dummy = new ListNode(-1), p = dummy;
    for(ListNode n : lists)
        if(n != null)
            pq.add(n);
    while(!pq.isEmpty()){
        ListNode n = pq.poll();
        p.next = n;
        p = p.next;
        if(n.next != null)
            pq.add(n.next);
    }
    return dummy.next;

}

results matching ""

    No results matching ""