Loading...
Loading...
A teacher on a college trip wants to sit in the middle coach of the train, so she can reach both ends quickly. If the train has two middle coaches, she picks the second one. Print the coach numbers from her coach to the end of the train. Try to find her coach while walking the list only once, without counting the coaches first.
Example 1
Input
5 1 2 3 4 5
Output
3 4 5
Coach 3 is the middle of five coaches, so the answer is 3 4 5.
Example 2
Input
6 10 20 30 40 50 60
Output
40 50 60
30 and 40 are both in the middle. She picks the second one, 40.
Try the problem first. Open one hint at a time.
Imagine two people walking the train together, one twice as fast as the other.
Start both at the head. Each step, move the slow one by one coach and the fast one by two coaches.
When the fast one cannot take another full step, the slow one is standing at the middle.
Keep going while fast != null && fast.next != null. This stops at the second middle for an even length.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor