Given the head of a singly linked list, you will traverse the list in contiguous groups of increasing size: the 1st group has size 1, the 2nd group has size 2, the 3rd group has size 3, and so on.
For each group:
Note: The final group may contain fewer nodes than its intended size; its actual length determines whether it should be reversed.
Return the head of the modified linked list.
head
— head node of a singly linked list.
List: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
[1]
,
[2,3]
,
[4,5,6]
,
[7,8,9]
(last group has length 3)
[2,3]
is even → becomes
[3,2]
; others unchanged
Result:
1 -> 3 -> 2 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
n
:
1 <= n <= 10^5
O(n)
time and
O(1)
extra space (excluding recursion stack).