Skip to content

Instantly share code, notes, and snippets.

@bachiri
Last active August 31, 2019 21:41
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 bachiri/64f82bb1a96ee215c47a8d412580bdc3 to your computer and use it in GitHub Desktop.
Save bachiri/64f82bb1a96ee215c47a8d412580bdc3 to your computer and use it in GitHub Desktop.
23. Merge k Sorted Lists /Leetcode
public class MergekSortedLists {
public static void main(String[] args) {
ListNode listNode = new ListNode(1);
listNode.next = new ListNode(4);
listNode.next.next = new ListNode(5);
ListNode secondListNode = new ListNode(1);
secondListNode.next = new ListNode(3);
secondListNode.next.next = new ListNode(4);
ListNode thirdListNode = new ListNode(2);
thirdListNode.next = new ListNode(6);
ListNode[] lists = {listNode, secondListNode, thirdListNode};
displayNodes(mergeKLists(lists));
}
public static ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> nodes = new PriorityQueue<>((o1, o2) -> o1.val - o2.val);
for (ListNode list : lists) {
ListNode current = list;
while (current != null) {
//All new Nodes Have a null next element so when building final linkedlist attribute the correct next element
nodes.add(new ListNode(current.val));
current = current.next;
}
}
ListNode root = nodes.poll();
ListNode current = root;
while (!nodes.isEmpty()) {
current.next = nodes.poll();
if (nodes.peek() != null) {
current = current.next;
}
}
return root;
}
public static void displayNodes(ListNode listNode) {
ListNode current = listNode;
while (current != null) {
System.out.print(" " + current.val + " ");
current = current.next;
}
}
public static class ListNode {
public int val;
public ListNode next;
public ListNode() {
}
public ListNode(int x) {
val = x;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment