
Think together · Start with a story
A girl stacks a red plate, then a blue one, then a yellow one. When she needs a plate, she takes one from the top.
Break down the process
- Add red plateAt the bottom
- Add blue plateOn top of red
- Add yellow plateAt the top
- Removal orderYellow, blue, red
A stack follows the last-in, first-out rule.
Push adds an element to the top; pop removes the top element. Function calls and matching parentheses are examples of problems that can use this order.
The last item added is the first one removed
Read from left to right as bottom to top. The rightmost item is the one you can remove.
The red plate is now at the top of the stack.
The blue plate becomes the new top.
The yellow plate was added last, so it comes off first.
The yellow plate is gone. Now the blue plate is at the top.
01What is a stack?
A stack is a data structure where adding and removing items happen at one end, called the top.
02Why is it like a pile of plates?
You add a plate to the top and take a plate from the top. The last plate you added is the first one you take away.
03What are push, pop, and top?
push
Put a new element on top of the stack.
pop
Remove the top element.
top
Look at the current top element.
04How does a stack change?
Each item enters and leaves from the top.
05What problems can stacks solve?
- Function call stacks
- Undo operations
- Matching parentheses
- Processing expressions
- Some implementations of DFS
06How do you use a stack in C++?
#include <stack>
std::stack<int> s;
s.push(10);
s.push(20);
std::cout << s.top(); // 20
s.pop();
pop() removes an element but does not return the removed value. If you need to use it, call top() first, then pop().
07Does a stack have to use contiguous memory?
No.
std::stack is a container adapter. By default, it usually uses std::deque as its underlying container, though other suitable containers can be used.
What you have learned
- A stack follows last-in, first-out.
- Its main operations happen at the top.
- push adds an item, pop removes one, and top looks at the top item.
- A stack is useful when the most recently added item should be handled first.
- The logical stack model is not the same as a specific memory layout.
Next: Queues: Like Waiting in Line to Buy a Ticket
Your turn to try
If you add 1 and then 2, which one do you remove first?
Ready? Open to see the explanation
2. It was added last, so it is at the top. After removing it, 1 becomes the top item.