Reverse Nodes in k-Group
Given the `head` of a linked list, reverse the nodes of the list `k` at a time, and return the modified list. `k` is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of `k` then left-out nodes, in the end, should remain as it is. You may not alter the values in the list's nodes, only nodes themselves may be changed.
Examples
Constraints
The number of nodes in the list is n.1 <= k <= n <= 50000 <= Node.val <= 1000
Iterative with Dummy Node (Optimal)
Approach
1. We use a `dummy` node that points to the `head` to handle the changing of the head node seamlessly. 2. We iterate through the list to count the total number of nodes. 3. We loop through the list again. As long as there are at least `k` nodes left, we reverse a group of `k` nodes. 4. To reverse a group, we use a standard linked list reversal. We maintain a `prevGroupTail` pointer (initially `dummy`) that connects to the new head of the reversed group. 5. Inside the group, we reverse `k` nodes, adjusting `next` pointers. 6. After reversing a group, the node that was originally the first in the group becomes the last, so it becomes our new `prevGroupTail` for the next iteration. 7. We decrement our node count by `k` and repeat until fewer than `k` nodes remain.
Complexity Analysis
This approach reverses in O(1) auxiliary space without using recursion.