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.
Quick Facts
FIFO — First In, First Out.
Insert at the rear and remove from the front.
Enqueue, dequeue, front/peek, and isEmpty.
Enqueue, dequeue, and front are typically O(1).
Beginner Rules
Add a new item to the rear of the queue.
Remove the front item and return it.
Look at the front item without removing it.
Dequeuing from an empty queue is an error, or returns nothing depending on implementation.
Stack vs Queue
LIFO — newest leaves first.
Works like a pile of plates.
Common in recursion, undo, and DFS.
FIFO — oldest leaves first.
Works like a line of people.
Common in BFS, scheduling, and buffering.
Why It’s Important
Jobs are processed in the order they arrive, so earlier requests are handled first.
CPU and task scheduling often rely on queue-like behavior to manage waiting work.
Packets often wait in queues before transmission, especially when traffic is busy.
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
Enqueue adds to the rear. Dequeue removes from the front.
Queues remove the oldest item first, while stacks remove the newest item first.
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.