What is a Stack?
A stack is a LIFO data structure where the last item added is the first item removed, fundamental to programming.
A stack is a data structure that follows Last-In-First-Out (LIFO) — like a stack of plates. You add plates to the top and take them from the top. The last plate you put on is the first one you take off.
Operations:
- Push: Add an item to the top
- Pop: Remove and return the top item
- Peek/Top: Look at the top item without removing it
- IsEmpty: Check if the stack is empty
Why It's Useful:
- Function calls: Programming languages use stacks to track function calls
- Undo operations: Stacks remember what you did
- Expression evaluation: Parsing mathematical expressions
- Backtracking: Solving problems by trying and undoing
Real-World Analogy:
Think of a browser's back button. Each page you visit gets "pushed" onto a stack. When you hit back, it "pops" the most recent page.
FAQ
What's the difference between a stack and a queue?
Stack is LIFO (last in, first out). Queue is FIFO (first in, first out) — like a line at a store.
Can stacks overflow?
Yes! Stack overflow happens when you try to push too many items. This is why infinite recursion crashes programs.