Two rules for one line
A queue adds at the back and takes from the front: first in, first out. A stack adds and takes at the top: last in, first out. The same steps can empty the two in a different order.
Keep the whole collection written down and update it after every step, arrivals included. When a step says take, look only at the end the rule names: the front of a queue, the top of a stack. If the collection is empty, nothing leaves.
The usual slip is to take the newest arrival from a queue, or the oldest item from a stack. Say the rule before each take.
1Write the collection after every step.
2Take from the front of a queue, the top of a stack.
3If it is empty, nothing leaves.
A stack, step by step
The stack starts with A at the bottom and B on top. Take: B is on top, so B leaves.
Add C: it goes on top of A. Take: C leaves.
Add D, then take: D leaves. The removal order is B, C, D, and A is still at the bottom.
A queue with arrivals
A queue starts with A at the front and B behind it. Then: take, add C, add D, take, take. Write the queue after each step.
- Take the next item
- Add C
- Add D
- Take the next item
- Take the next item
Try it
Which item leaves on the last take?
- C
- D
Show the answer
C
Right. A leaves first. C and D join at the back, so the queue is B, C, D. The next take gives B and the last gives C. D is still waiting.
Enable JavaScript to answer interactively and save your place.
Practice Manage the waiting line