This question evaluates proficiency with singly linked list manipulation, pointer/reference management, in-place group operations, and complexity reasoning including time and constant extra space.
You are given the head of a singly linked list and an integer k (k >= 1).
Reverse the nodes of the list in-place in groups of size k:
k
nodes should be reversed as a group.
k
, leave those nodes in their original order.
You may assume the list nodes are defined in the usual way, for example:
struct ListNode { int val; ListNode* next; };
class ListNode { int val; ListNode next; }
Input list (values):
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7, and k = 3
Output list should be:
3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 7
(1, 2, 3)
are reversed to
(3, 2, 1)
.
(4, 5, 6)
are reversed to
(6, 5, 4)
.
7
is fewer than
k
nodes, so it stays as is.
n
can be up to around
10^5
.
O(1)
extra space (excluding recursion stack if you choose a recursive solution).
O(n)
time.
Describe your algorithm and then implement a function that performs this transformation.