Stack (LIFO)
Stack (LIFO)
Section titled “Stack (LIFO)”Last In, First Out.
Operations
Section titled “Operations”- Push ’ O(1)
- Pop ’ O(1)
- Peek ’ O(1)
Example Flow
Section titled “Example Flow”push(10) ' [10]push(20) ' [10, 20]push(30) ' [10, 20, 30]pop() ' [10, 20]peek() ' 20JavaScript Implementation
Section titled “JavaScript Implementation”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; }}Real-World Uses
Section titled “Real-World Uses”- Undo/Redo
- Browser history
- Function calls
- Expression evaluation
Related Topics
Section titled “Related Topics”- Queue (FIFO) — LIFO’s counterpart, used for BFS and task scheduling
- Graphs — DFS traversal uses a stack (implicitly via recursion or explicitly)