#K39577. Reverse Linked List in Groups
Reverse Linked List in Groups
Reverse Linked List in Groups
Given a singly linked list with ( n ) nodes and an integer ( k ), your task is to reverse the nodes of the list in groups of size ( k ). If the number of nodes is not a multiple of ( k ), then the remaining nodes at the end are left as is.
For example, if the list is [1, 2, 3, 4, 5, 6, 7, 8] and ( k = 3 ), then the output should be [3, 2, 1, 6, 5, 4, 7, 8].
Formally, if the list is represented as ( L = [l_1, l_2, \ldots, l_n] ), then for each valid group ( i ) (where ( (i-1)\times k + 1 \leq n )), if ( i\times k \leq n ) then the block ( [l_{(i-1)k+1}, \ldots, l_{ik}] ) is reversed; otherwise, it remains unchanged.
inputFormat
The input is given via standard input (stdin) and consists of three parts:
1. The first line contains a single integer ( n ) representing the number of nodes in the linked list.
2. The second line contains ( n ) space-separated integers, representing the values of the nodes in order.
3. The third line contains a single integer ( k ), the size of each group for the reversal.
outputFormat
Output the modified linked list after reversing every group of ( k ) nodes. The values should be printed on a single line separated by spaces.## sample
8
1 2 3 4 5 6 7 8
3
3 2 1 6 5 4 7 8