1
1
package com .thealgorithms .datastructures .lists ;
2
2
3
3
/**
4
- * Reverse K Group LinkedList (https://www.topcoder.com/thrive/articles/reverse-node-in-k-group)
4
+ * The ReverseKGroup class provides functionality to reverse nodes in a
5
+ * linked list in groups of k nodes.
6
+ * <p>
7
+ * This algorithm follows the approach of reversing the linked list in segments of
8
+ * size k. If the remaining nodes are fewer than k, they remain unchanged.
9
+ * </p>
10
+ * <p>
11
+ * Example:
12
+ * Given a linked list: 1 -> 2 -> 3 -> 4 -> 5 and k = 3,
13
+ * the output will be: 3 -> 2 -> 1 -> 4 -> 5.
14
+ * </p>
15
+ * <p>
16
+ * The implementation contains:
17
+ * - {@code length(Node head)}: A method to calculate the length of the linked list.
18
+ * - {@code reverse(Node head, int count, int k)}: A helper method that reverses the nodes
19
+ * in the linked list in groups of k.
20
+ * - {@code reverseKGroup(Node head, int k)}: The main method that initiates the reversal
21
+ * process by calling the reverse method.
22
+ * </p>
23
+ * <p>
24
+ * Complexity:
25
+ * <ul>
26
+ * <li>Time Complexity: O(n), where n is the number of nodes in the linked list.</li>
27
+ * <li>Space Complexity: O(1), as we are reversing in place.</li>
28
+ * </ul>
29
+ * </p>
30
+ *
5
31
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
6
32
*/
7
-
8
33
public class ReverseKGroup {
34
+
35
+ /**
36
+ * Calculates the length of the linked list.
37
+ *
38
+ * @param head The head node of the linked list.
39
+ * @return The total number of nodes in the linked list.
40
+ */
9
41
public int length (Node head ) {
10
42
Node curr = head ;
11
43
int count = 0 ;
@@ -15,7 +47,15 @@ public int length(Node head) {
15
47
}
16
48
return count ;
17
49
}
18
- // reverse function
50
+
51
+ /**
52
+ * Reverses the linked list in groups of k nodes.
53
+ *
54
+ * @param head The head node of the linked list.
55
+ * @param count The remaining number of nodes.
56
+ * @param k The size of the group to reverse.
57
+ * @return The new head of the reversed linked list segment.
58
+ */
19
59
public Node reverse (Node head , int count , int k ) {
20
60
if (count < k ) {
21
61
return head ;
@@ -37,9 +77,16 @@ public Node reverse(Node head, int count, int k) {
37
77
}
38
78
return prev ;
39
79
}
80
+
81
+ /**
82
+ * Reverses the linked list in groups of k nodes.
83
+ *
84
+ * @param head The head node of the linked list.
85
+ * @param k The size of the group to reverse.
86
+ * @return The head of the modified linked list after reversal.
87
+ */
40
88
public Node reverseKGroup (Node head , int k ) {
41
89
int count = length (head );
42
- Node ans = reverse (head , count , k );
43
- return ans ;
90
+ return reverse (head , count , k );
44
91
}
45
92
}
0 commit comments