File tree 1 file changed +54
-0
lines changed
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Arrays ;
2
+ import java .util .Comparator ;
3
+ import java .util .PriorityQueue ;
4
+
5
+ /**
6
+ * @author Arun Pandey (https://github.com/pandeyarun709)
7
+ */
8
+ public class Merge_K_SortedLinkedlist {
9
+
10
+ /**
11
+ * This function merge K sorted LinkedList
12
+ *
13
+ * @param a array of LinkedList
14
+ * @param N size of array
15
+ * @return node
16
+ */
17
+ Node mergeKList (Node [] a , int N ) {
18
+ // Min Heap
19
+ PriorityQueue <Node > min = new PriorityQueue <>(Comparator .comparingInt (x -> x .data ));
20
+
21
+ // adding head of all linkedList in min heap
22
+ min .addAll (Arrays .asList (a ).subList (0 , N ));
23
+
24
+ // Make new head among smallest heads in K linkedList
25
+ Node head = min .poll ();
26
+ min .add (head .next );
27
+ Node curr = head ;
28
+
29
+ // merging LinkedList
30
+ while (!min .isEmpty ()) {
31
+
32
+ Node temp = min .poll ();
33
+ curr .next = temp ;
34
+ curr = temp ;
35
+
36
+ // Add Node in min Heap only if temp.next is not null
37
+ if (temp .next != null ) {
38
+ min .add (temp .next );
39
+ }
40
+ }
41
+
42
+ return head ;
43
+ }
44
+
45
+ private class Node {
46
+ private int data ;
47
+ private Node next ;
48
+
49
+ public Node (int d ) {
50
+ this .data = d ;
51
+ next = null ;
52
+ }
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments