Reverse Nodes in k-Group
You are given the head of a singly linked list and an integer k.
Reverse the list in consecutive blocks of exactly k nodes:
- If a block has exactly
knodes, reverse the order of nodes inside that block. - If the remaining nodes at the end are fewer than
k, keep them in their original order. - You may only rearrange node links. Do not change node values.
Return the head of the updated linked list.
Examples
Input: [[1,2,3,4,5],2]
Output: []
Input: [[1,2,3,4,5],3]
Output: []
Hints
Start by traversing the linked list to count the total number of nodes. This will help determine how many full blocks of size `k` exist.
For each full block of size `k`, reverse the nodes within that block by adjusting the `next` pointers of the nodes. Ensure the reversed block is properly connected to the previous and next blocks.
After processing all full blocks, if there are remaining nodes (fewer than `k`), traverse them without reversing and connect them to the last reversed block. Handle edge cases where the list length is a multiple of `k` or where `k` is 1.
Reverse Nodes in k-Group
You are given the head of a singly linked list and an integer `k`.