reverseInGroups<T> function
Reverses a linked list in groups of specified size
head - The head of the linked list
k - The size of each group to reverse
Returns the new head of the linked list
Time Complexity: O(n) where n is the length of the list Space Complexity: O(1)
Implementation
LinkedListNode<T>? reverseInGroups<T>(LinkedListNode<T>? head, int k) {
if (head == null || k <= 1) return head;
LinkedListNode<T>? current = head;
LinkedListNode<T>? prev;
LinkedListNode<T>? next;
int count = 0;
// Reverse first k nodes
while (current != null && count < k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
// Recursively reverse the remaining nodes
if (next != null) {
head.next = reverseInGroups(next, k);
}
return prev;
}