Reverse the nodes of the list k at a time. If fewer than k nodes remain at the end, leave them as they are.
DSA Animator › DSA Revision › Linked List › Reverse Nodes in K-Group
Remember: count k, reverse k, reconnect, repeat. A short tail stays untouched. The video solves Reverse Nodes in K-Group (LeetCode 25, Hard) with the Pointer Reversal pattern from the Linked List topic, and you can replay every step in the interactive Reverse Nodes in K-Group animation.
Reverse the nodes of the list k at a time. If fewer than k nodes remain at the end, leave them as they are.
For 1, 2, 3, 4, 5 with k equal to 2, the result is 2, 1, 4, 3, 5.
Copying groups into arrays and rewriting values uses extra space. We can reverse each group in place.
Keep a pointer to the node before the current group. Check that k nodes exist ahead, and stop if they do not. Reverse those k nodes, connect them back, and jump to the end of the group.
The first group is 1 and 2, which becomes 2, 1. The next group is 3 and 4, which becomes 4, 3. Only 5 is left, fewer than k, so it stays. The result is 2, 1, 4, 3, 5.
In code, start with a dummy, and group previous at the dummy. Find the k-th node, and stop if it is null. Reverse the group with the standard loop, then reconnect its head and tail. It's O of n time and O of 1 space.
Remember: count k, reverse k, reconnect, repeat. A short tail stays untouched.