Skip to main content
CSData StructuresInteractiveBeginner

Stack vs Queue

KO: 스택 vs 큐·EN: Stack vs Queue·JA: スタック vs キュー·LIFO vs FIFO

Comparing Stack (Last-In, First-Out) and Queue (First-In, First-Out) linear data structures and their access rules

Table of Contents

Interactive Playground

Tap or drag to interact with the demo
Quick Answer

What is Stack vs Queue?

Comparing Stack (Last-In, First-Out) and Queue (First-In, First-Out) linear data structures and their access rules. It is a core concept in Data Structures within CS.

Core Principles

Stacks and Queues are fundamental linear data structures distinguished by where elements enter and leave:

  • Stack (LIFO — Last-In, First-Out): Like a stack of plates, both push (insert) and pop (remove) happen at the same top end. Ideal whenever you need to unwind or backtrack to the most recent state.
  • Queue (FIFO — First-In, First-Out): Like a checkout line, elements enqueue at the rear and dequeue from the front. Essential whenever tasks must be processed fairly in arrival order.

Practical Takeaways

  • Avoid Array.shift() for large queues: While push/pop give true O(1) stack operations in JavaScript arrays, calling shift() to dequeue forces every remaining item to shift left—degrading to O(N). Use a circular buffer or linked list for high-throughput queues.
  • Pair with the right graph traversal: Depth-First Search (DFS) naturally uses a stack (or the call stack via recursion), while Breadth-First Search (BFS) relies on a queue to discover shortest paths level by level.
  • Bound your production queues: Unbounded in-memory queues can trigger out-of-memory crashes under traffic spikes. Always configure a max capacity and explicit backpressure behavior.

Notable Examples

  • Stack in action: Program execution call stacks, editor Undo/Redo histories (Ctrl+Z), browser navigation history, and expression parsing.
  • Queue in action: OS thread scheduling, message brokers (Kafka, RabbitMQ, SQS), printer spoolers, and the JavaScript Event Loop task queue.
  • Deque (Double-Ended Queue): Supports O(1) insertion and removal at both ends, powering sliding-window algorithms.

Practical Code Snippet

Copy and drop straight into your project
stack-queue.tsTypeScript
// Stack (LIFO: Last In, First Out) — Undo historyconst stack: string[] = [];stack.push("step-1", "step-2");const lastAction = stack.pop(); // "step-2" // Queue (FIFO: First In, First Out) — Task schedulingconst queue: string[] = [];queue.push("job-1", "job-2");const nextJob = queue.shift(); // "job-1"