Sub topic 1
Last in, first out: the idea behind a stack
Prerequisites
This chapter assumes you can write functions and simple classes in one language, use lists or arrays with indexing, and read basic Big-O notation such as O(1) and O(n). The examples use Python.
The LIFO principle
A stack is a collection where the most recently added item is the first one removed. This rule is called last in, first out, or LIFO.
A stack of plates is the usual picture. You add a clean plate to the top, and you take a plate from the top. You don't pull one from the middle. The plate you placed last is the plate you take first.
Two rules define the behavior:
- New items go on one end only, called the top.
- Items leave from that same end.
Because both actions use the top, the order of removal is the reverse of the order of insertion.
A first example in Python
A Python list already behaves like a stack if you only use one end. append adds at the end, and pop removes from the end. Here the end of the list is the top.
stack = []
stack.append("A")
stack.append("B")
stack.append("C")
print(stack.pop()) # C
print(stack.pop()) # B
print(stack.pop()) # AThe output is C, B, A. This is the reverse of the input order, which is the main property of a stack.
Where LIFO shows up
LIFO matches problems where the most recent unfinished thing must be dealt with first. Later chapters cover these in detail:
- Function calls. The function that was called last must finish before its caller can continue.
- Nested brackets. The most recently opened bracket must be closed first.
- Undo history. The latest action is the first one undone.
- Backtracking. When a path fails, you return to the most recent choice point.
In each case, a pending task waits until everything started after it has finished.
Stack versus queue
A queue is the opposite ordering. It is first in, first out (FIFO), like a line at a shop. Choose a stack when the newest item should be handled first. Choose a queue when the oldest should be handled first.
| Property | Stack | Queue |
|---|---|---|
| Order | Last in, first out | First in, first out |
| Add at | Top | Back |
| Remove from | Top | Front |
| Typical use | Undo, call tracking, bracket matching | Task scheduling, buffering |
Common mistakes
- Reading from the wrong end. If you store items in a list, decide which end is the top and use only that end. Using
pop(0)on a Python list removes the first item, which turns it into a queue and costs O(n) because the remaining items shift. - Reaching into the middle. If you index into the middle of a collection, you aren't using it as a stack. A stack exposes only the top.
- Popping an empty stack. Removing from an empty stack is an error. Later chapters cover how to handle it.
Exercise
You push the numbers 1, 2, 3, 4 onto an empty stack in that order, then pop twice, then push 5, then pop once. What value does the last pop return, and what remains on the stack from bottom to top?
Show answer
The last pop returns 5. After pushing 1, 2, 3, 4, the two pops remove 4 then 3, leaving 1, 2. Pushing 5 gives 1, 2, 5. The final pop removes 5, so the stack holds 1, 2 from bottom to top.
Exercise
A list holds ["x", "y", "z"], and you want to use it as a stack with its end as the top. Which call removes and returns the top item, and what does it return?
Show answer
Call pop() with no argument. It removes and returns "z", the last item added.