Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 7, 2017 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/1c975be88cc6afd26826f33e415061b0 to your computer and use it in GitHub Desktop.
Save InterviewBytes/1c975be88cc6afd26826f33e415061b0 to your computer and use it in GitHub Desktop.
Merge K sorted linked lists
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
import java.util.Comparator;
import java.util.PriorityQueue;
public class MergeKLists {
private static final Comparator<ListNode> COMPARATOR = new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
};
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(COMPARATOR);
for (ListNode listNode : lists) {
if (listNode != null) priorityQueue.offer(listNode);
}
ListNode sentinel = new ListNode(0);
ListNode current = sentinel;
while (!priorityQueue.isEmpty()) {
ListNode node = priorityQueue.poll();
current.next = node;
current = current.next;
if (node.next != null) priorityQueue.offer(node.next);
}
return sentinel.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment