Loading...
Loading...
A railway yard builds a train behind an engine. A coach can be attached at the back or right behind the engine, and the first coach with a given name can be removed. The engine itself is never removed.
Write a class Coach with fields name and next (the Coach behind it, or null) and constructors Coach(String name, Coach next) and Coach(String name), which calls the first with null. Write a class Train whose constructor Train(String engine) creates the engine coach, with methods addFront, addBack, boolean remove(String name) and String text().
front NAME, back NAME, remove NAME or show.remove: REMOVED NAME or NOT FOUND NAME. For show: the names joined by -, starting with the engine, then | k where k is the number of coaches (not counting the engine). Other commands print nothing.remove only looks at coaches, never the engineExample
Input
ENG 5 back S1 back S2 front A1 remove S1 show
Output
REMOVED S1 ENG-A1-S2 | 2
A1 goes right behind the engine; removing S1 joins A1 to S2.
Try the problem first. Open one hint at a time.
new Coach(name, engine.next) makes a coach that already points at the old first coach; then set engine.next to it.
For addBack, walk with Coach c = engine; while (c.next != null) c = c.next; and attach there.
To remove, stop at the coach before the one to remove and set prev.next = prev.next.next.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor