Detaching train cars with a pointer to a pointer
There is a train of numbered cars linked in a line.
At first it has no cars.
There are five commands.
- front x: attach a new car numbered x at the front.
- back x: attach a new car numbered x at the back.
- cut x: detach the first car numbered x, looking from the front.
If there is no such car, do nothing.
- rev: reverse the order of the whole train.
- show: print on one line the current number of cars k followed by the k car numbers from the front, separated by single spaces.
If there are no cars, print just 0.
The first line gives the number of commands q, and the next q lines give one command each.
Try solving it with a linked list where each car holds its number and a pointer to the next car.
Carry the train as a pointer head to the first car and a pointer to a pointer tailp that points to the last car's next slot.
Write cut without treating the first car specially: make it a function that walks by moving Node **pp, the address of "the pointer that points to the current car".
- Input
- 1 ≤ q ≤ 10,000, 1 ≤ x ≤ 9,999.
Allshowcommands together print at most 30,000 car numbers.showappears at least once. - Output
- One line per
show
9 back 3 front 1 back 7 cut 3 show rev back 2 cut 1 show
2 1 7 2 7 2