wayetan
1/5/2014 - 9:47 AM

Merge k Sorted Lists

Merge k Sorted Lists

/**
 * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
 */
 
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists == null || lists.isEmpty()) 
            return null;
        PriorityQueue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){
            public int compare(ListNode o1, ListNode o2) {
                return o1.val > o2.val ? 1 : (o1.val < o2.val ? -1 : 0);
            }
        });
        for (ListNode node : lists) {
            if (node != null) {
                heap.add(node);
            }
        }
        ListNode head = null, cur = null;
        while (!heap.isEmpty()) {
            if (head == null) {
                head = heap.poll();
                cur = head;
            } else {
                cur.next = heap.poll();
                cur = cur.next;
            }
            if (cur.next != null) {
                heap.add(cur.next);
            }
        }
        return head;
    }
}