CAP7004 · Unit 2: Linear data structures
Stacks and their applications
8 practice questions
Key points
- LIFO; push, pop, peek are O(1)
- Call stack, undo, bracket matching, expression evaluation
- Postfix: pop right operand first
- Underflow = pop empty, overflow = push full
A stack is a Last-In-First-Out (LIFO) structure. Main operations: push (add on top), pop (remove top), peek (read top), is_empty. In Python a list works: append pushes and pop() pops, both O(1).
Applications:
- Function calls: the call stack stores return addresses and local variables.
- Undo in editors and browser back history.
- Balanced brackets: push openers; on a closer, pop and compare. The string is balanced only if all pairs match and the stack ends empty.
{[()]}is balanced;([)],((and())are not. - Postfix evaluation: scan tokens; push operands; for an operator pop
bthena, pusha op b. Example2 3 4 * +gives 2 + 3*4 = 14. - Infix to postfix: output operands; keep operators on a stack by precedence (
*/above+-).a+b*cbecomesabc*+;(a+b)*cbecomesab+c*.
Overflow happens when pushing to a full fixed-size stack; underflow when popping an empty one.
Exam pitfall: in postfix, the first popped value is the right operand, so 6 2 - is 6 - 2 = 4, not 2 - 6.
Try two questions
After push(1), push(2), push(3), pop(), the top of the stack is:
- 3
- 1
- 2
- Empty
Show the answer
C. 3 was removed, leaving 2 on top.
The value of the postfix expression 2 3 4 * + is:
- 20
- 24
- 9
- 14
Show the answer
D. 3*4 = 12, then 2 + 12 = 14.