Skip to content
Velloreth
Programming 7 min read

Stacks and Queues Explained With Real Use Cases

Stacks are last-in-first-out and queues are first-in-first-out. Learn how both work, how to implement them, and where each appears in real software.

By

Two structures, one idea

A stack and a queue are both collections with a restricted access pattern. You can only add at one end and remove from one end. That restriction is the point: it makes the behaviour predictable and the implementation simple.

The difference is which end.

  • A stack adds and removes at the same end. Last in, first out.
  • A queue adds at one end and removes at the other. First in, first out.

Everything else follows from that.

Stacks: last in, first out

A stack supports three operations, all O(1):

  • push — add an item to the top
  • pop — remove and return the top item
  • peek — return the top item without removing it
class Stack {
  #items = [];

  push(item) { this.#items.push(item); }
  pop() { return this.#items.pop(); }
  peek() { return this.#items[this.#items.length - 1]; }
  get size() { return this.#items.length; }
  get isEmpty() { return this.#items.length === 0; }
}

In JavaScript, an array already is a stack — push and pop are both O(1) amortised. You rarely need a wrapper class, though one can make intent clearer.

Where stacks appear

The call stack. Every function call pushes a frame; every return pops one. This is not a metaphor — it is literally a stack, and it is why recursion depth is bounded. A recursion 10,000 levels deep has 10,000 frames alive, which is why it overflows.

Undo and redo. Each action is pushed onto an undo stack. Undo pops from it and pushes onto a redo stack. Redo pops from the redo stack.

Balanced brackets. The classic parsing exercise:

function isBalanced(str) {
  const stack = [];
  const pairs = { ')': '(', ']': '[', '}': '{' };
  for (const ch of str) {
    if ('([{'.includes(ch)) stack.push(ch);
    else if (ch in pairs) {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.length === 0;
}

Expression evaluation. Converting infix to postfix and evaluating postfix both use a stack. This is how calculators and compilers handle operator precedence.

Depth-first search. The recursive form uses the call stack; the iterative form uses an explicit one. Either way, the traversal order comes from last-in-first-out behaviour.

Browser history. The back button pops the history stack.

Syntax highlighting and parsing. Nested structures — HTML tags, JSON objects, code blocks — are matched with a stack.

Queues: first in, first out

A queue supports:

  • enqueue — add an item to the back
  • dequeue — remove and return the item at the front
  • peek — return the front item without removing it
class Queue {
  #items = new Map();
  #head = 0;
  #tail = 0;

  enqueue(item) { this.#items.set(this.#tail++, item); }
  dequeue() {
    if (this.#head === this.#tail) return undefined;
    const item = this.#items.get(this.#head);
    this.#items.delete(this.#head++);
    return item;
  }
  get size() { return this.#tail - this.#head; }
}

The Map plus index pointers avoids the O(n) cost of Array.prototype.shift. That cost is worth understanding: shift removes the first element and then moves every remaining element down one index, which is O(n). A queue that dequeues n times is therefore O(n²) — a real performance bug in code that looks innocent.

Where queues appear

Task scheduling. Background jobs are processed in submission order. A job queue is the backbone of any system that does work asynchronously.

Breadth-first search. Visit all neighbours of a node before going deeper. BFS finds shortest paths in unweighted graphs precisely because it explores in distance order.

Message brokers. RabbitMQ, Kafka, and SQS are queues at scale. Producers enqueue, consumers dequeue, and the queue absorbs bursts.

Print spoolers. Documents print in submission order.

Rate limiting. A sliding window of recent request timestamps is a queue: enqueue on each request, dequeue anything older than the window.

Buffering. Streaming video buffers ahead in a queue so playback is smooth when the network stutters.

Request handling. Web servers accept connections into a queue and hand them to workers.

The deque

A deque (double-ended queue) allows O(1) insertion and removal at both ends. It generalises both structures: restrict it to one end and you have a stack; restrict it to opposite ends and you have a queue.

// JavaScript has no built-in deque, but the pattern is:
class Deque {
  #items = new Map();
  #head = 0;
  #tail = 0;

  pushBack(item) { this.#items.set(this.#tail++, item); }
  pushFront(item) { this.#items.set(--this.#head, item); }
  popBack() { return this.#items.get(--this.#tail); }
  popFront() { return this.#items.get(this.#head++); }
}

Deques are the right structure for sliding-window problems. The classic is “maximum of every window of size k”:

function maxSlidingWindow(nums, k) {
  const result = [];
  const deque = []; // stores indices, values decreasing
  for (let i = 0; i < nums.length; i++) {
    while (deque.length && deque[0] <= i - k) deque.shift();
    while (deque.length && nums[deque[deque.length - 1]] <= nums[i]) deque.pop();
    deque.push(i);
    if (i >= k - 1) result.push(nums[deque[0]]);
  }
  return result;
}

The naive approach is O(nk). The deque version is O(n), because each index enters and leaves the deque at most once.

Priority queues

A priority queue removes the highest-priority item rather than the oldest. It is not a queue in the FIFO sense, but it belongs in this family because it is what you reach for when FIFO is not the right order.

It is implemented with a heap, giving O(log n) insertion and removal and O(1) access to the extreme element.

// Conceptual: a min-heap priority queue
// push(item, priority) -> O(log n)
// pop() -> returns the item with the smallest priority, O(log n)

Use cases: task schedulers that run urgent jobs first, Dijkstra’s algorithm, event simulation, and top-k problems.

Implementing a queue with two stacks

A classic interview question with a real lesson: you can build a queue from two stacks.

class QueueFromStacks {
  #inbox = [];
  #outbox = [];

  enqueue(item) { this.#inbox.push(item); }

  dequeue() {
    if (this.#outbox.length === 0) {
      while (this.#inbox.length) this.#outbox.push(this.#inbox.pop());
    }
    return this.#outbox.pop();
  }
}

Push onto the inbox. When dequeuing, if the outbox is empty, pour the inbox into it — which reverses the order — then pop. Each element moves at most twice, so the amortised cost is O(1) per operation.

The lesson is that the two structures are not as different as they look. Reversing a sequence turns one into the other.

Choosing between them

You need to…Use
Undo the last actionStack
Match nested brackets or tagsStack
Traverse depth-firstStack
Evaluate expressionsStack
Process in arrival orderQueue
Traverse breadth-firstQueue
Buffer a streamQueue
Slide a window over dataDeque
Always handle the most urgent firstPriority queue

Common mistakes

Using shift() for dequeue. O(n) per call, O(n²) overall. Use a deque or index pointers.

Assuming a stack is a queue. They are not interchangeable. If order matters, the choice is not stylistic.

Forgetting to check for empty. pop() on an empty stack returns undefined in JavaScript, which can propagate silently. In other languages it throws or is undefined behaviour.

Using a queue where a priority queue is needed. If some jobs must run first, FIFO will starve them.

Recursing deeply instead of using an explicit stack. The call stack is finite. For deep traversals, an explicit stack on the heap is safer.

For how these fit with the other structures, see data structures every developer should know and trees and graphs explained, which covers the traversals these structures enable. For the complexity reasoning, Big-O notation explained.

Quotable summary

A stack is last-in-first-out, supporting O(1) push, pop, and peek at one end; it powers the call stack, undo, bracket matching, expression evaluation, and depth-first traversal. A queue is first-in-first-out, supporting O(1) enqueue and dequeue at opposite ends; it powers task scheduling, message brokers, buffering, rate limiting, and breadth-first traversal. A queue built on a plain array has O(n) dequeue because removing the first element reindexes the rest, so real queues use a linked list, a deque, or index pointers. A deque generalises both with O(1) operations at either end and is the right structure for sliding-window problems. A priority queue removes by priority rather than arrival order and is implemented with a heap.

Frequently asked questions

What is the difference between a stack and a queue?
A stack removes the most recently added item first, like a pile of plates, while a queue removes the oldest item first, like a line at a checkout. Stacks are used for undo and recursion; queues are used for scheduling and buffering.
What are the main operations on a stack?
Push adds an item to the top, pop removes and returns the top item, and peek returns the top item without removing it. All three are O(1).
Why is Array.shift() slow for queues?
Because removing the first element of an array requires shifting every remaining element down one position, which is O(n). Use a linked list, a deque, or an index pointer instead for O(1) dequeue.
What is a real-world example of a stack?
The browser back button. Each page you visit is pushed onto a history stack, and pressing back pops the most recent one. Undo in an editor works the same way.
What is a real-world example of a queue?
A printer spooler. Documents are printed in the order they were submitted, so the first job sent is the first one printed. Background job systems and message brokers work the same way.
What is a priority queue?
A priority queue removes the highest-priority item rather than the oldest, regardless of arrival order. It is usually implemented with a heap, giving O(log n) insertion and removal instead of O(1).