All problems

Problem 123

Reverse Nodes in K-Group

Hard · 30 pts · Linked List, Recursion

Problem

You are given a linked list and a number K. Split the list into consecutive groups of K nodes, reverse the order of the nodes inside each group, and print the result. If the last group has fewer than K nodes, leave it in its original order. For each group, first check that K more nodes exist. If they do, reverse those K nodes in place as in the usual list reversal, and connect the end of the previous group to the new front of this group.

Input

First line: integers N and K. Second line: the N node values.

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

1 <= K <= N <= 5000; 0 <= value <= 1000

Example input

5 2
1 2 3 4 5

Example output

2 1 4 3 5

Explanation

With K = 2, the list 1 2 3 4 5 splits into (1 2), (3 4) and the short group (5). Reversing the full groups gives 2 1 and 4 3, while 5 stays, so the result is 2 1 4 3 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Swap Nodes in Pairs Next: Merge K Sorted Lists