Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){
public int compare(ListNode a, ListNode b){
return a.val - b.val;
}
});
for(ListNode node : lists){
if(node != null){
queue.add(node);
}
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while(!queue.isEmpty()){
tail.next = queue.poll();
tail = tail.next;
if(tail.next != null){
queue.add(tail.next);
}
}
return dummy.next;
}