Example 1
- Input
- head = [1,2,3,4,5], k = 2
- Output
- [2,1,4,3,5]
Reverse the complete pairs of original nodes [1,2] and [3,4]. The final node 5 cannot form a pair, so its next link remains null.
Given the head of a linked list and an integer k, reverse the nodes k at a time, leaving fewer than k trailing nodes as they are, using only pointer changes.
Given the head of a linked list, reverse its nodes k at a time and return the modified list.
If fewer than k nodes remain at the end, leave them as they are. Only node links may change, never node values.
Reverse the complete pairs of original nodes [1,2] and [3,4]. The final node 5 cannot form a pair, so its next link remains null.
Reverse the first complete group of three. The trailing nodes 4 and 5 form a short group: keep 4 -> 5 -> null unchanged and connect the new tail 1 to node 4.
A one-node group is already reversed. Return the same node with its value and null next link unchanged.
The entire list is one complete group. The original head 1 becomes the last node and must point to null.
A full group can be reversed by changing its links, but its original first node becomes its new tail. In Example 1, reversing nodes 1 and 2 creates 2 -> 1; node 1 must then connect to the next reversed group, 4 -> 3. Keep the boundary after each group before rewiring anything. If the suffix has fewer than k nodes, keep every link in that suffix unchanged. Node identity matters: swapping values would produce the same numbers but violate the requirement.
Reveal Recursive Groups: intuition, complexity, and code
For group operations on a linked list, first prove that the group is complete, then preserve its outside boundary before rewiring. The old head becomes the reversed group tail, so reconnect both ends and advance from that tail. A dummy node makes the first group follow the same rules as later groups; recursion instead stores the pending tail connections on its stack.