23. Merge k Sorted Lists
Input:
[1->4->5, 1->3->4,2->6]
Output:
1->1->2->3->4->4->5->6/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length ==0) return null;
PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.length, (n1, n2)-> n1.val - n2.val);
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
for(ListNode node : lists){
if (node != null)
queue.add(node);
}
while(!queue.isEmpty()){
cur.next = queue.poll(); //link
cur = cur.next;
if(cur.next != null){ // put successor in the queue
queue.add(cur.next);
}
}
return dummy.next;
}
}Last updated
Was this helpful?