Skip to content

Stack (LIFO)

Last In, First Out.

  • Push ’ O(1)
  • Pop ’ O(1)
  • Peek ’ O(1)
push(10) ' [10]
push(20) ' [10, 20]
push(30) ' [10, 20, 30]
pop() ' [10, 20]
peek() ' 20
class Stack {
constructor() {
this.items = [];
}
push(value) {
this.items.push(value);
}
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;
}
}
  • Undo/Redo
  • Browser history
  • Function calls
  • Expression evaluation

  • Queue (FIFO) — LIFO’s counterpart, used for BFS and task scheduling
  • Graphs — DFS traversal uses a stack (implicitly via recursion or explicitly)