#K88162. Reverse Alternate K Nodes in a Linked List

    ID: 37248 Type: Default 1000ms 256MiB

Reverse Alternate K Nodes in a Linked List

Reverse Alternate K Nodes in a Linked List

You are given a singly linked list containing n nodes and an integer k. Your task is to reverse every alternate group of k nodes in the list. Specifically, you should:

  • Reverse the first k nodes if there are exactly k nodes available.
  • Leave the next k nodes unchanged.
  • Continue this pattern until you reach the end of the list.

Note: If the number of remaining nodes is less than k, leave them as they are (i.e. do not reverse).

This problem can be mathematically described as: given a linked list L and a positive integer k, partition L into segments of size k and apply reversal only to every alternate segment.

The input is provided via standard input and the output via standard output.

inputFormat

The input consists of three lines:

  1. The first line contains an 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.
  3. The third line contains the integer k.

You can assume that n >= 0 and k > 0.

outputFormat

Output a single line containing the modified linked list's node values separated by a single space, after reversing every alternate group of k nodes.

## sample
9
1 2 3 4 5 6 7 8 9
3
3 2 1 4 5 6 9 8 7