← Back

Stack

LIFOsequentialrecursive
Press play to start
1class Stack<T> {
2 private items: T[] = []
3 push(item: T): void { this.items.push(item) }
4 pop(): T | undefined { return this.items.pop() }
5 peek(): T | undefined { return this.items[this.items.length - 1] }
6 isEmpty(): boolean { return this.items.length === 0 }
7 size(): number { return this.items.length }
8}
9const stack = new Stack<number>()
10stack.push(10); stack.push(20); stack.push(30)
11stack.peek() // 30
12stack.pop() // 30
Step 1/0

Complexity

Best:O(1)
Average:O(1)
Worst:O(1)
Space:O(n)

Description

A Last-In-First-Out (LIFO) data structure. Elements are added and removed from the same end (top).

When to use

Function call management, undo operations, expression evaluation, backtracking algorithms (DFS), and browser history.