合并k个排序链表

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

Definition for singly-linked list.
public class ListNode {

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

ListNode dummy=new ListNode(0);
ListNode tail=dummy;

for(ListNode node:lists)
{
if(node!=null)
queue.add(node);
}
while(!queue.isEmpty())
{
tail.next=queue.poll();
tail=tail.next;
if(tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}

思路:
使用了优先权队列,采取了最小堆的策略,每次队列弹出的都是最小的数据。