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; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists==null || lists.length==0) {
        	return null;
        }
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {

			@Override
			public int compare(ListNode o1, ListNode o2) {
				if (o1.val < o2.val) {
					return -1;
				} else if (o1.val > o2.val) {
					return 1;
				} else {
					return 0;
				}
			}
		});
        for (ListNode list : lists) {
        	if (list == null) {
        		continue;
        	}
        	queue.add(list);
        }
        ListNode head = new ListNode(0);
        ListNode curNode = head;
        while (!queue.isEmpty()) {
        	ListNode t = queue.poll();
    		curNode.next = t;
        	curNode = t;
        	if (t.next != null) {
        		queue.add(t.next);
        	}
        }
        return head.next;
    }
}

 

你可能感兴趣的:(merge)