The goal is to reverse the nodes of a linked list in groups of size k. If the remaining number of nodes is less than k, they should stay in their original order.
We do this by identifying chunks of size k, reversing them, and reconnecting the reversed parts back into the main list.
For each group of size k:
Find the groupEnd.
Temporarily break the connection to the rest of the list.
Reverse the group.
Reconnect the reversed group to the list.
Update prevGroupTail and groupStart to process the next group.
Complexity
Space Complexity
Time Complexity
Code
// Helper function to reverse a linked list starting from 'node'
void reverse(ListNode node) {
ListNode previous = null;
while (node != null) {
ListNode nextNode = node.next;
node.next = previous;
previous = node;
node = nextNode;
}
}
public ListNode reverseKGroup(ListNode head, int k) {
// No need to process if k <= 1 or list is empty
if (k <= 1 || head == null) return head;
// Dummy node simplifies edge cases (e.g. reversing at head)
ListNode dummyNode = new ListNode(-1, head);
ListNode prevGroupTail = dummyNode;
ListNode groupStart = head;
while (groupStart != null) {
ListNode groupEnd = groupStart;
int count = k;
// Find the end node of the current group
while (count > 1 && groupEnd != null) {
groupEnd = groupEnd.next;
count--;
}
// If the group is smaller than k, no reversal needed
if (groupEnd == null) break;
// Detach the group and save the remaining list
ListNode nextGroupStart = groupEnd.next;
groupEnd.next = null;
// Reverse the current group
reverse(groupStart);
// Connect the previous group to the new head of this group
prevGroupTail.next = groupEnd;
// Connect the tail of the reversed group to the next part
groupStart.next = nextGroupStart;
// Update pointers for next iteration
prevGroupTail = groupStart;
groupStart = nextGroupStart;
}
return dummyNode.next;
}