A stack is a linear data structure where the last value added is the first value removed.
This rule is called LIFO, which means Last In, First Out.
Core operations
push(value)adds a value to the top.pop()removes the top value.peek()reads the top value without removing it.isEmpty()checks whether the stack has no values.
Mental model
Think of a stack as a pile of plates. You add a new plate on top, and you remove the top plate first.
top
9
5
2
bottom
JavaScript implementation
class Stack {
constructor() {
this.items = [];
}
push(value) {
this.items.push(value);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
}
Where stacks show up
Stacks are useful when the newest unfinished task must be handled first.
- Undo and redo
- Browser history
- Function call stack
- Parentheses validation
- Depth-first search
Complexity
- Push:
O(1) - Pop:
O(1) - Peek:
O(1) - Search by value:
O(n)
Practice links
Use the visualizer below to push and pop from the top.
Interactive walkthrough
Stack Visualizer
Push and pop values from the top of the stack.