1
- import java .util .*;
1
+ import java .util .Arrays ;
2
+ import java .util .Comparator ;
3
+ import java .util .PriorityQueue ;
2
4
5
+ /**
6
+ * @author Arun Pandey (https://github.com/pandeyarun709)
7
+ */
3
8
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
- {
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 ) {
14
18
// 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
-
19
+ PriorityQueue <Node > min = new PriorityQueue <>(Comparator .comparingInt (x -> x .data ));
20
+
22
21
// adding head of all linkedList in min heap
23
- for (int i =0 ; i < N ;i ++)
24
- {
25
- min .add (a [i ]);
26
- }
27
-
22
+ min .addAll (Arrays .asList (a ).subList (0 , N ));
23
+
28
24
// Make new head among smallest heads in K linkedList
29
25
Node head = min .poll ();
30
26
min .add (head .next );
31
27
Node curr = head ;
32
28
33
- //merging LinkedList
34
- while (!min .isEmpty ()) {
35
-
29
+ // merging LinkedList
30
+ while (!min .isEmpty ()) {
31
+
36
32
Node temp = min .poll ();
37
33
curr .next = temp ;
38
34
curr = temp ;
39
-
40
- //Add Node in min Heap only if temp.next is not null
41
- if (temp .next != null ){
35
+
36
+ // Add Node in min Heap only if temp.next is not null
37
+ if (temp .next != null ) {
42
38
min .add (temp .next );
43
39
}
44
40
}
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
- }
41
+
42
+ return head ;
61
43
}
62
44
63
- }
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
+ }
0 commit comments