Stack - Last In, First Out (LIFO)#
A stack allows adding and removing only at one end, the top - like a pile of plates in a wedding buffet.
| Operation | Meaning | Time |
|---|---|---|
push(x) |
put x on top | O(1) |
pop() |
remove the top | O(1) |
top() |
look at the top | O(1) |
empty(), size() |
checks | O(1) |
Where stacks are used: Undo/Redo in editors, the browser Back button, the function call stack, checking brackets in code, converting and evaluating expressions, and depth-first search.
A stack from an array#
top = 30 after pop, top = 20
std::stack - Undo in a text editor#
typed: "Learn" typed: "Learn DSA" typed: "Learn DSA at" typed: "Learn DSA at Vindhyaedu" undo: "Learn DSA at" undo: "Learn DSA"
Stack = थालियों का ढेर। जो थाली सबसे बाद में रखी, वही सबसे पहले उठेगी (LIFO)। इसीलिए editor का Undo stack से बनता है - आखिरी बदलाव सबसे पहले हटता है।
Queue - First In, First Out (FIFO)#
A queue adds at the back and removes from the front - like the line at a railway ticket counter.
| Operation | std::queue |
Time |
|---|---|---|
| add at the back | push(x) |
O(1) |
| remove from the front | pop() |
O(1) |
| look at the front / back | front(), back() |
O(1) |
Where queues are used: printer jobs, call-centre waiting lines, CPU task scheduling, message queues between servers, and breadth-first search.
Preparing order 101 Preparing order 102 Preparing order 103 Preparing order 104 1 2 3 4
priority_queue is a special queue where the largest (or smallest) item always comes out first - used for hospital emergency queues, Dijkstra's shortest path and top-k problems.
Classic problem: next greater element#
For every price, find the next higher price to its right (or -1). A brute force is O(n²); a monotonic stack does it in O(n).
4 -> 5 5 -> 25 2 -> 25 25 -> -1 7 -> -1 6 -> -1
Each index is pushed and popped at most once, so the total work is O(n).
Summary#
- Stack = LIFO (
push,pop,top); Queue = FIFO (push,pop,front). All O(1). - Stacks: undo, back button, call stack, brackets, DFS, monotonic-stack problems.
- Queues: scheduling, buffering, BFS;
dequeworks at both ends;priority_queueserves the biggest first.