Reverse in Groups of K
You are given a singly linked list with n nodes. Each node has a distinct id, an integer value, and the id of the next node in the list (or -1 if it is the last node). The nodes are given in arbitrary order, not necessarily the order they appear in the list, so you first have to follow the next pointers from the head to recover the actual sequence.
Walk the list from the head and split it into consecutive groups of k nodes: the first k nodes form the first group, the next k nodes form the second group, and so on. Reverse the order of the nodes inside every group that contains exactly k nodes. If the list length is not a multiple of k, the last group has fewer than k nodes — leave that trailing group exactly as it is, and do not reverse it. The groups keep their original positions along the list; only the order of nodes within each full group changes.
Print the values of the nodes in the resulting list, from head to tail.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ n).
Each of the next n lines contains three integers id, value, next describing one node:
id(1 ≤ id ≤ n) is the node's id. Every id from1tonappears exactly once across these lines.value(-10^9 ≤ value ≤ 10^9) is the node's value.nextis the id of the node that follows this one in the list, or-1if this node is the last one.
These n lines may appear in any order, independent of the list order.
The last line contains one integer head (1 ≤ head ≤ n), the id of the first node of the list.
The given next pointers, starting from head, form a single chain that visits all n nodes exactly once and ends at the node whose next is -1. There are no cycles and no branches.
Output
Print n integers — the values of the list after reversing every full group of k consecutive nodes — separated by single spaces, on one line.
Notes
In the first example the list, in order, has values 10 20 30 40 50 and k = 2. The groups are [10, 20], [30, 40] and [50]. The first two groups are full and get reversed to [20, 10] and [40, 30]; the last group has only one node, so it is left alone. The result is 20 10 40 30 50.
In the second example k equals n, so the whole list is a single full group and gets reversed.