Foundation

Queue (Abstract Data Type)

A queue stores items using FIFO — First In, First Out. Items enter at the rear and leave from the front.

Queues are core to many real systems: scheduling, printers, customer service lines, networking, and simulation. In algorithms, queues are essential for BFS and level-by-level processing.

This page teaches the queue mental model and the 3 core operations: enqueue, dequeue, and front / peek.

Access Pattern
FIFO
Entry / Exit
Rear / Front
Core Operations
Enqueue, Dequeue, Peek
Typical Cost
O(1)

Quick Facts

Access Pattern

FIFO — First In, First Out.

Where Operations Happen

Insert at the rear and remove from the front.

Common Operations

Enqueue, dequeue, front/peek, and isEmpty.

Time Cost

Enqueue, dequeue, and front are typically O(1).

Beginner Rules

1
Enqueue

Add a new item to the rear of the queue.

2
Dequeue

Remove the front item and return it.

3
Front / Peek

Look at the front item without removing it.

4
Underflow

Dequeuing from an empty queue is an error, or returns nothing depending on implementation.

The key rule to remember: the oldest item leaves first. A queue processes items in arrival order.

Stack vs Queue

Stack

LIFO — newest leaves first.
Works like a pile of plates.
Common in recursion, undo, and DFS.

Queue

FIFO — oldest leaves first.
Works like a line of people.
Common in BFS, scheduling, and buffering.

Why It’s Important

Print Jobs

Jobs are processed in the order they arrive, so earlier requests are handled first.

Scheduling

CPU and task scheduling often rely on queue-like behavior to manage waiting work.

Networking

Packets often wait in queues before transmission, especially when traffic is busy.

BFS Reasoning

Breadth-first search explores nodes level by level, which naturally matches queue behavior.

Visualization

Use this visualization to follow the FIFO rule in action: the first item added is the first one removed. Watch how enqueue happens at the rear and dequeue happens at the front.

Common Mistakes

Confusing Enqueue vs Dequeue

Enqueue adds to the rear. Dequeue removes from the front.

Confusing FIFO vs LIFO

Queues remove the oldest item first, while stacks remove the newest item first.

Dequeuing an Empty Queue

Always check isEmpty() first, or handle underflow safely in your implementation.

Outcome

After this lesson, learners should be able to describe FIFO, correctly apply enqueue, dequeue, and front / peek, and recognize queues in real applications like scheduling, networking, BFS, and everyday line-based systems.