File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 12
12
13
13
package chapter03linkedlists ;
14
14
15
+ import java .util .ArrayList ;
16
+ import java .util .PriorityQueue ;
17
+
15
18
public class MergeKSortedLists {
16
19
//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
+ }
17
54
}
You can’t perform that action at this time.
0 commit comments