Loading problem...
You are given the head node of a singly linked list. Your task is to reverse the nodes of this list in groups of exactly k consecutive nodes at a time, then return the head of the transformed list.
The reversal should be applied segment by segment, where each segment consists of k consecutive nodes. If at any point fewer than k nodes remain at the end of the list (a partial segment), those leftover nodes should retain their original order and not be reversed.
Important Constraint: You must manipulate the actual node references and pointers to achieve the reversal. Simply swapping or modifying the data values stored within the nodes is not a valid solution. The structural connections between nodes must be physically rearranged.
head = [1,2,3,4,5]
k = 2[2,1,4,3,5]The list is divided into segments of 2: [1,2], [3,4], and [5]. The first segment [1,2] reverses to [2,1]. The second segment [3,4] reverses to [4,3]. The third segment contains only 1 node, which is less than k=2, so it remains unchanged as [5]. The final result is [2,1,4,3,5].
head = [1,2,3,4,5]
k = 3[3,2,1,4,5]The list is divided into segments of 3: [1,2,3] and [4,5]. The first segment [1,2,3] reverses to [3,2,1]. The second segment [4,5] has only 2 nodes, which is less than k=3, so it remains unchanged. The final result is [3,2,1,4,5].
head = [1,2,3,4]
k = 4[4,3,2,1]The entire list has exactly 4 nodes, which equals k=4. All nodes form a single complete segment that gets reversed entirely. The result is [4,3,2,1].
Constraints