Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Show Company Tags Show Tags Show Similar Problems
Solution
/**
* 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;
Queue<ListNode> queue = new PriorityQueue<ListNode>((a, b) -> (Integer.compare(a.val, b.val)));
ListNode dummy = new ListNode(0);
ListNode iter = dummy;
for(ListNode node: lists) {
if(node != null) queue.offer(node);
}
while(!queue.isEmpty()) {
ListNode node = queue.poll();
if(node.next != null) queue.offer(node.next);
iter.next = node;
iter = iter.next;
}
iter.next = null;
return dummy.next;
}
}