Skip to content

Commit 9dabdd9

Browse files
committed
Merge pull request careermonk#7 from Amay22/master
Added function to merge multiple sorted LL using Priority Queue.
2 parents cd0ad17 + 94dba9a commit 9dabdd9

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/chapter03linkedlists/MergeKSortedLists.java

+37
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,43 @@
1212

1313
package chapter03linkedlists;
1414

15+
import java.util.ArrayList;
16+
import java.util.PriorityQueue;
17+
1518
public class MergeKSortedLists {
1619
//Refer Priority Queues
20+
public static ListNode mergeKLists(ArrayList<ListNode> lists) {
21+
if (lists.isEmpty()) {
22+
return null;
23+
}
24+
//PriorityQueue is a sorted queue
25+
PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.size(), (ListNode a, ListNode b) -> {
26+
if (a.getData() > b.getData) {
27+
return 1;
28+
} else if (a.getData() == b.getData()) {
29+
return 0;
30+
} else {
31+
return -1;
32+
}
33+
});
34+
//add first node of each list to the queue
35+
for (ListNode list : lists) {
36+
if (list != null) {
37+
pq.add(list);
38+
}
39+
}
40+
ListNode head = new ListNode(0);
41+
ListNode p = head;
42+
while (pq.size() > 0) {
43+
//poll() retrieves and removes the head of the queue - q.
44+
ListNode temp = pq.poll();
45+
p.next = temp;
46+
//keep adding next element of each list
47+
if (temp.next != null) {
48+
pq.add(temp.next);
49+
}
50+
p = p.next;
51+
}
52+
return head.next;
53+
}
1754
}

0 commit comments

Comments
 (0)