Master the Last-In-First-Out (LIFO) principle and discover how stacks power everything from function calls to expression evaluation and undo operations in modern software.
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.
Add an element to the top of the stack
stack.push(element)
Time: O(1) | Space: O(1)
Remove and return the top element
element = stack.pop()
Time: O(1) | Space: O(1)
View the top element without removing it
element = stack.peek()
Time: O(1) | Space: O(1)
Check if the stack has no elements
boolean = stack.isEmpty()
Time: O(1) | Space: O(1)
class ArrayStack {
constructor(capacity = 100) {
this.items = new Array(capacity);
this.top = -1;
this.capacity = capacity;
}
push(element) {
if (this.top >= this.capacity - 1) {
throw new Error("Stack Overflow");
}
this.items[++this.top] = element;
}
pop() {
if (this.isEmpty()) {
throw new Error("Stack Underflow");
}
return this.items[this.top--];
}
peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.top];
}
isEmpty() {
return this.top === -1;
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedStack {
constructor() {
this.top = null;
this.size = 0;
}
push(element) {
const newNode = new Node(element);
newNode.next = this.top;
this.top = newNode;
this.size++;
}
pop() {
if (this.isEmpty()) {
throw new Error("Stack Underflow");
}
const data = this.top.data;
this.top = this.top.next;
this.size--;
return data;
}
peek() {
return this.isEmpty() ? null : this.top.data;
}
isEmpty() {
return this.top === null;
}
}
Programming languages use call stacks to manage function calls, local variables, and return addresses.
Convert infix expressions to postfix and evaluate mathematical expressions using stacks.
Text editors and applications use stacks to implement undo/redo functionality.
Web browsers use stacks to track page navigation and implement back button functionality.
Validate balanced parentheses, brackets, and braces in code and mathematical expressions.
Operating systems use stacks for memory allocation and managing program execution contexts.