Stacks
Lesson 11 of 20Push, pop and peek your way to LIFO mastery — then watch the call stack juggle function frames in 3D.
Meet the stack
A stack is a pile where only the top is ever touched. Whatever went in last comes out first — that rule powers everything from Ctrl+Z to function calls.
LIFO rule
Last In, First Out. Push 12 then 7, and the first pop hands you back 7 — the newest value always leaves first.
Three O(1) moves
push places a value on top, pop removes it, peek just reads it. None of them ever shift the other elements.
Where you meet it
Undo history, the browser back button, matching brackets and the function call stack are all stacks doing their thing.
Two homes
An array with a top index or a linked list with a head pointer — both implement the same stack interface.
Overflow is literal
Push onto a full stack and you get the error that gave this website its name: stack overflow.
Push & pop live
One slot of contact — watch values stack up and leave in reverse order.
An empty stack — top is -1. Values will land here one on top of another.
Bracket checker flow
The classic interview question: is "{[()]}" balanced? The stack decides.
Walkthrough
An array-backed stack with push and pop — plus the bracket checker in action.
1#include <iostream>2using namespace std;34int stk[5];5int top = -1;67void push(int v) {8if (top == 4) { cout << "full" << endl; return; }9stk[++top] = v;10}1112int pop() {13if (top == -1) return -1;14return stk[top--];15}1617int main() {18push(12);19push(7);20push(21);21cout << pop() << endl;22cout << pop() << endl;23return 0;24}
stk reserves 5 integer slots — the stack’s body.
Call stack in 3D
Every function call pushes a frame; every return pops one — spin the pile around.
Predict the output
Manual push/pop with ++top and top-- — trace every line.
1#include <iostream>2using namespace std;34int main() {5int stk[10];6int top = -1;78stk[++top] = 4;9stk[++top] = 9;10stk[++top] = 2;11cout << stk[top--] << endl;12cout << stk[top--] << endl;13cout << top << endl;14return 0;15}
Hint: ++top increments BEFORE using it, top-- uses the old value first. The final print shows what remains.
Concept check
Click a term, then click its meaning to lock the pair.
Key takeaways
A stack touches only the top: push, pop and peek are all O(1).
LIFO order — the value pushed last is the first one out.
top = -1 means empty; pushing onto a full array stack overflows.
Undo history, back buttons and the function call stack are real-world stacks.
Balanced-bracket checking is the classic interview use of a stack.
Arrays and linked lists both implement stacks — the interface is what matters.