Back to Visualizer
Stack (LIFO)
A Last-In-First-Out (LIFO) data structure. The last element added is the first one to be removed. Think of a stack of plates!
Push: O(1)Pop: O(1)Peek: O(1)
Speed:
TOP
10
20
30
← TOP
BOTTOM
Default
Top
Pushing
Popping
Peeking
3
Current Size
10
Max Size
Stack Operations
- Push: Add element to top
- Pop: Remove element from top
- Peek: View top element without removing
- isEmpty: Check if stack is empty
- isFull: Check if stack is full
Real-World Uses
- • Undo/Redo functionality
- • Browser back button
- • Function call stack
- • Expression evaluation
- • Parenthesis matching
Complexity
PushO(1)
PopO(1)
PeekO(1)
SpaceO(n)
Code
class Stack {
constructor(maxSize = 10) {
this.items = [];
this.maxSize = maxSize;
}
push(value) {
if (this.isFull()) {
throw new Error("Stack Overflow");
}
this.items.push(value);
}
pop() {
if (this.isEmpty()) {
throw new Error("Stack Underflow");
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
isFull() {
return this.items.length >= this.maxSize;
}
size() {
return this.items.length;
}
}