11package com .thealgorithms .datastructures .lists ;
22
33/**
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+ *
531 * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
632 */
7-
833public 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+ */
941 public int length (Node head ) {
1042 Node curr = head ;
1143 int count = 0 ;
@@ -15,7 +47,15 @@ public int length(Node head) {
1547 }
1648 return count ;
1749 }
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+ */
1959 public Node reverse (Node head , int count , int k ) {
2060 if (count < k ) {
2161 return head ;
@@ -37,9 +77,16 @@ public Node reverse(Node head, int count, int k) {
3777 }
3878 return prev ;
3979 }
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+ */
4088 public Node reverseKGroup (Node head , int k ) {
4189 int count = length (head );
42- Node ans = reverse (head , count , k );
43- return ans ;
90+ return reverse (head , count , k );
4491 }
4592}
0 commit comments