Last active
August 31, 2019 21:41
-
-
Save bachiri/64f82bb1a96ee215c47a8d412580bdc3 to your computer and use it in GitHub Desktop.
23. Merge k Sorted Lists /Leetcode
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
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