/**
* 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.size()==0){
return null;
}
PriorityQueue<ListNode> queue=new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
return o1.val<o2.val?-1:o1.val==o2.val?0:1;
}
});
//新建一个头结点
ListNode newhead=new ListNode(0);
ListNode newtail=newhead;
//把list中的第一个node依次加入优先级队列
for(ListNode tempnode:lists){
if(tempnode!=null){
queue.add(tempnode);
}
}
while(!queue.isEmpty()){
newtail.next=queue.poll();
newtail=newtail.next;
//如果该条链表后续还有结点,添加进优先级队列
if(newtail.next!=null){
queue.add(newtail.next);
}
}
return newhead.next;
}
}