Loading...
Loading...
A parcel train is loaded at a platform in groups of k coaches, starting from the front. For loading, the yard turns around the order of the coaches inside every full group of k. If fewer than k coaches are left at the end, they stay in their order. The train is a linked list, so change the links instead of making new nodes. Print the coach numbers from front to back after all the groups are turned.
Example 1
Input
8 1 2 3 4 5 6 7 8 3
Output
3 2 1 6 5 4 7 8
Groups 1 2 3 and 4 5 6 are turned around. Only 7 and 8 are left, fewer than 3, so they stay.
Example 2
Input
6 10 20 30 40 50 60 2
Output
20 10 40 30 60 50
Every pair swaps places.
Try the problem first. Open one hint at a time.
Use a dummy node before the head. Keep groupPrev: the node just before the group you are about to turn.
From groupPrev, step forward k times. If you hit null first, fewer than k coaches are left, so stop.
Turn the k coaches around with the usual three references. Start prev at the node after the group, so the group's new last coach already links to what follows.
Link groupPrev to the group's new first coach. The group's old first coach is now its last, so it becomes the next groupPrev.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor