#K9351. Reverse Nodes in k-Group

    ID: 38435 Type: Default 1000ms 256MiB

Reverse Nodes in k-Group

Reverse Nodes in k-Group

You are given a singly linked list and an integer k. Your task is to reverse the nodes of the list in groups of size k and output the modified list. If the last group contains fewer than k nodes, leave the group as is.

The reversal must be performed in-place with O(n) time complexity and constant extra memory. Formally, for a linked list \(L = l_1 \rightarrow l_2 \rightarrow \ldots \rightarrow l_n\) and an integer \(k\), you need to transform it into:

[ \begin{cases} l_k \rightarrow l_{k-1} \rightarrow \ldots \rightarrow l_1 \rightarrow l_{k+1} \rightarrow \ldots, & \text{if } n \ge k,\ l_1 \rightarrow l_2 \rightarrow \ldots \rightarrow l_n, & \text{if the remaining nodes are less than } k. \end{cases} ]

Read the linked list and integer k from standard input, perform the group reversal, and then print the resulting linked list to standard output (all on one line, with nodes separated by a single space).

inputFormat

The input is provided via standard input (stdin) and formatted as follows:

  1. An integer n representing the number of nodes in the linked list.
  2. A line with n space-separated integers representing the node values.
  3. An integer k on a new line representing the group size for reversal.

outputFormat

Print the modified linked list to standard output (stdout) as a single line with the node values separated by a single space.

## sample
5
1 2 3 4 5
2
2 1 4 3 5

</p>