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