Stack Basics
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. Think of it like a stack of plates - you can only add or remove plates from the top.
Core Operations
- Push: Add an element to the top of the stack - O(1)
- Pop: Remove and return the top element - O(1)
- Peek/Top: View the top element without removing it - O(1)
- isEmpty: Check if the stack is empty - O(1)
When to Use Stacks
Stacks are ideal when you need to:
- Track the most recent item
- Reverse a sequence
- Match pairs (like parentheses)
- Implement undo functionality
- Parse expressions
Implementation in JavaScript
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) return null;
return this.items.pop();
}
peek() {
if (this.isEmpty()) return null;
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
Python Implementation
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
return None
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
Key Insight
Stacks naturally reverse order - the first item pushed is the last item popped. This property makes them perfect for problems involving reversal or backtracking.