What is a stack?
A stack follows last in, first out (LIFO): the most recently added item is the first one removed, like a pile of plates. You can only touch the top.
Stacks power undo history, the browser back button, expression evaluation and the call stack that keeps track of function calls in your programs.
Time complexity
| Operation | Time | Notes |
|---|---|---|
| Push | O(1) | Adds an item on top |
| Pop | O(1) | Removes the top item |
| Peek | O(1) | Reads the top without removing it |
| Search | O(n) | Items below the top are not directly reachable |
Try it yourself
- Push until the stack is full to see overflow.
- Pop on an empty stack to see underflow.
- Change Stack size and watch the tube resize.
- Press Display stack to print the contents from top to bottom.
Stack vs queue
Both add and remove in O(1), but a stack serves the newest item first while a queue serves the oldest first. Use a stack for undo and backtracking, and a queue for fair, in-order processing.
Common questions
- What does LIFO mean?
- Last in, first out: the item pushed most recently is the first one popped.
- What is stack overflow?
- It happens when you push onto a stack that has no room left. In programs it often means too many nested function calls.
- What are stacks used for?
- Undo and redo, backtracking, parsing and evaluating expressions, depth-first search and the call stack.