-
-
Save InterviewBytes/1c975be88cc6afd26826f33e415061b0 to your computer and use it in GitHub Desktop.
Merge K sorted linked lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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