Concept Flow - Queue vs Stack When to Use Which
Start Operation
Is order First-In-First-Out?
Yes No
Use Queue
Use Stack
Decide data structure based on order needed: FIFO means Queue, LIFO means Stack.
const stack: number[] = []; stack.push(1); stack.push(2); const last = stack.pop(); console.log(stack); const queue: number[] = []; queue.push(1); queue.push(2); const first = queue.shift(); console.log(queue);
| Step | Operation | Data Structure | Pointer Changes | Visual State |
|---|---|---|---|---|
| 1 | Push 1 | Stack | Top points to 1 | [1] |
| 2 | Push 2 | Stack | Top points to 2 | [1, 2] |
| 3 | Pop | Stack | Top moves from 2 to 1 | [1] |
| 4 | Push 1 | Queue | Rear points to 1 | [1] |
| 5 | Push 2 | Queue | Rear points to 2 | [1, 2] |
| 6 | Shift (dequeue) | Queue | Front moves from 1 to 2 | [2] |
| 7 | End | - | - | Stack: [1], Queue: [2] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | After Step 5 | After Step 6 | Final |
|---|---|---|---|---|---|---|---|---|
| stack | [] | [1] | [1, 2] | [1] | [1] | [1] | [1] | [1] |
| queue | [] | [] | [] | [] | [1] | [1, 2] | [2] | [2] |
| stack top | null | 1 | 2 | 1 | 1 | 1 | 1 | 1 |
| queue front | null | null | null | null | 1 | 1 | 2 | 2 |
| queue rear | null | null | null | null | 1 | 2 | 2 | 2 |
Queue vs Stack Quick Guide: - Queue: First-In-First-Out (FIFO) - Stack: Last-In-First-Out (LIFO) - Use Queue when order matters (like waiting lines) - Use Stack for undo actions or backtracking - Push adds, pop removes top (Stack) - Push adds, shift removes front (Queue)
stack?push() adds an element to the end (top) of the array acting as a stack.const queue: number[] = []; queue.push(1); queue.push(2); queue.push(3); const first = queue.shift(); console.log(queue);
const stack: number[] = []; stack.push(10); stack.push(20); const top = stack.shift(); console.log(top);
Pass the test and this pattern moves unknown