Loading...
Loading...
The guard of a goods train reports that the k-th coach counted from the back has a fault, so it must be taken out. The train is a linked list from the front coach. Remove that coach by changing one link, and print the train that is left. Try to do it while walking the list only once. Print EMPTY if no coach is left.
EMPTY if no coach is left.Example 1
Input
5 1 2 3 4 5 2
Output
1 2 3 5
Counting from the back, coach 5 is first and coach 4 is second, so coach 4 is removed.
Example 2
Input
3 7 8 9 3
Output
8 9
The 3rd coach from the back is the front coach, so the train now starts at 8.
Try the problem first. Open one hint at a time.
If one reference starts k coaches ahead of another and both move together, the gap between them stays k.
When the front reference reaches the end, the back reference is k coaches behind the end.
To remove a coach you need the coach just before it. Start the back reference at a dummy node placed before the head.
The dummy node also handles removing the first coach: the answer is always dummy.next.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor