Reverse Nodes in k-Group

HardLinked List
Next
Linked ListPointer Reversal

Reverse the nodes of a linked list k at a time and print the result. If the number of remaining nodes at the end is less than k, leave them as they are. You may only change links, not values. The values are given as an array; build the linked list from them yourself, then solve it with pointers.

Input

Line 1: n. Line 2: the n node values. Line 3: k.

Output

Print the resulting list's values on one line.

Constraints

1 <= k <= n <= 5000

Example 1
Input
5
1 2 3 4 5
2
Output
2 1 4 3 5

Groups of two: (2 1) (4 3), and 5 is left alone.

Example 2
Input
5
1 2 3 4 5
3
Output
3 2 1 4 5

The first three flip to 3 2 1; the last two are fewer than k.

Hints

Reverse Nodes in k-Group - Hard Linked List Problem | Skill Shiksha