Loading...
Loading...
At a terminal station the railway yard turns a train around, so the last coach becomes the first one. In the yard records the train is a linked list: each coach knows only the coach right behind it. Change the links so the list runs in the opposite direction, without making new coaches. Then print the coach numbers from the new front to the new back.
Example 1
Input
5 11 12 13 14 15
Output
15 14 13 12 11
Coach 15 was at the back, so it is now at the front.
Example 2
Input
2 7 3
Output
3 7
With two coaches, they simply swap places.
Try the problem first. Open one hint at a time.
Walk the list from the head. At each coach, make its link point to the coach before it instead of the coach after it.
Once you change curr.next, you can no longer reach the rest of the train. Save curr.next in a variable first.
Keep three references: the previous coach, the current coach and the saved next coach. The previous coach starts as null.
When the current coach becomes null, the previous coach is the new head.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor