- Describe a stack as a last-in, first-out structure
- Trace push, pop and peek operations
- Handle stack overflow and underflow
- Give real uses of stacks
You can use arrays or lists, and you know that functions call other functions while a program runs.
Last in, first out
A stack is a collection where items are added and removed at the same end, called the top. Imagine a pile of plates: you put a new plate on top, and you take the top plate first. This rule is called last in, first out, or LIFO.
A last-in, first-out data structure with access only at the top.
Last in, first out: the newest item is the first to be removed.
Stack operations
Push adds an item to the top. Pop removes and returns the top item. Peek shows the top item without removing it. Pushing to a full fixed-size stack causes overflow, and popping from an empty stack causes underflow. Programs check for both.
Start with an empty stack. Push 3, push 8, pop, push 5. What is on the stack?
push 3 → [3] push 8 → [3, 8] pop → [3] returns 8 push 5 → [3, 5]
Answer: The stack holds 3 and 5, with 5 on top.
Undo features, browser back buttons and function calls all use stacks.
Practice
Quick check
What does LIFO stand for?
After push A, push B, pop, which item is left?
Which feature commonly uses a stack?
- A stack is last in, first out.
- Push adds, pop removes and peek looks at the top.
- Overflow and underflow must be handled.
- Undo and function calls use stacks.
