Queue, step by step.

A queue is a linear data structure that adds items at the rear and removes them from the front, so the first item in is the first out (FIFO). On a circular array or a linked list, enqueue, dequeue and peek all take O(1) time. This page explains how it works, with step-by-step animations of a printer queue, a web server's request queue and a linked-list-based queue from the VisiGrab app.

How a queue works

What is a queue in data structures?

A queue is a linear data structure that adds items at one end, the rear, and removes them from the other, the front, so the first item in is the first out (FIFO). It is an abstract data type (ADT): an array or a linked list can sit underneath, and the app builds it both ways. Front and rear are also called head and tail.

FIFO: first in, first out

The first item added is the first one removed, as in a line at a counter. Enqueue 1, 2 and 3, and 1 comes out first. A stack, which is LIFO, would return 3 first.

Queue operations: enqueue, dequeue and peek

Enqueue adds an item at the rear. Dequeue removes the front item and returns it. Peek, also called front, returns the front item and leaves it in place. Rear, or back, reads the last item. isEmpty and size tell whether the queue holds items and how many, and a bounded queue also has isFull. On a circular array or a linked list, each takes O(1) time, amortized when a dynamic array has to grow or shrink. There is no access by index. On an empty queue, dequeue and peek fail: this is underflow.

A horizontal queue of six slots. From the right end it holds 7, 4, 2 and 0, and the two slots on the left are empty. A rear label with a curved arrow sits at the left end, where enqueue adds items, and a front label with a curved arrow at the right end, where dequeue removes them.

Enqueue adds a random number at the rear, Dequeue removes the number at the front, so the oldest number leaves first.

A shared printer may be busy when a document arrives. A print queue, kept by the print spooler, holds such documents, so nobody has to send one again. In the player, two computers send four documents, and the printer prints them in the order they arrived.

A printer queue

All steps as text
  1. Let's imagine a scenario where multiple users share a single printer in an office or home setting.
  2. When a user sends a document to the printer, it may already be busy printing another document. Instead of forcing the user to wait and try again, the printer uses a queue to manage incoming documents.
  3. The printer processes the documents in the order they arrive, following the First-In-First-Out (FIFO) principle. It takes the document at the front of the queue (dequeues) and starts printing it.
  4. Once a document is completed, the printer moves on to the next document in the queue, if any.
  5. If there are no documents in the queue, the printer remains idle until a new document is added to the queue.
  6. The four documents were printed in the order they arrived, and the queue is empty: the first document queued was the first one printed.
A printer queue. Last step: The four documents were printed in the order they arrived, and the queue is empty: the first document queued was the first one printed.

Queue example: a web server

A web server keeps incoming requests in a request queue, in the order received. A pool of worker threads or processes takes them from the front. In the player, three clients send requests, the middle one first; the requests queue in order of arrival, not top to bottom, and the workers take them from the front in that order.

A web server's request queue

All steps as text
  1. Let's see another example, where a web server uses a queue to manage incoming requests efficiently.
  2. When clients send requests to the web server, these requests are enqueued in the request queue, maintaining the order in which they were received.
  3. The web server has a pool of worker threads (or processes) that are responsible for processing the requests. Each worker thread dequeues a request from the front of the queue and processes it.
  4. Once the processing is complete, the worker thread sends the response back to the client.
  5. The requests left the queue in the order they arrived: the middle client's, the top client's, then the bottom client's. Every client got its response.
A web server's request queue. Last step: The requests left the queue in the order they arrived: the middle client's, the top client's, then the bottom client's. Every client got its response.

When every worker is busy, new requests wait in the queue. Thread pools, task queues and message queues such as RabbitMQ follow the same producer–consumer pattern.

Array-based queue: the circular queue

In a linear queue on a plain array, dequeue would shift every item one cell left, as in deleting from the beginning of an array: O(n). Moving a front index forward instead is O(1), but the freed cells are never reused. Once rear reaches the last cell, the array looks full while cells at the start are free: a false overflow. A circular queue fixes both. It keeps the items in a circular buffer, or ring buffer, and wraps each index with the modulo operator: rear = (rear + 1) % capacity on enqueue, front = (front + 1) % capacity on dequeue. Both stay O(1), and every cell is reused.

Eight array cells, indices 0 to 7, arranged in a ring with arrows running clockwise. Cell 5 holds 27 and is marked front. Cells 6, 7, 0 and 1 hold 14, 88, 5 and 10, and cell 1 is marked rear. Cells 2, 3 and 4 are empty.

Enqueue adds a random number at the rear, Dequeue removes the number at the front. The array works as a ring: after the last cell comes the first.

Wrapped indices alone cannot tell a full queue from an empty one. The app's code starts with rear = -1, so its rear marks the last item, and it keeps a size count: the queue is full when size == capacity. Another convention keeps rear at the next free cell and leaves one cell empty: the queue is empty when front == rear and full when (rear + 1) % capacity == front. The app's dynamic version doubles a full array, copying the items in queue order. It halves the array at a quarter full; halving at half full would make alternating enqueues and dequeues resize every time. In the app you can enqueue and dequeue on a circular array and watch the markers wrap.

Linked-list-based queue

A linked-list-based queue keeps each item in a node with a link to the next. It uses a double-ended linked list: front links to the first node, where dequeue removes, and rear to the last, where enqueue adds. The other way round is slow: removing the last node needs the node before it, an O(n) walk. In the player, 4 is dequeued from 4, 5, 0, 1, and 7 is enqueued, leaving 5, 0, 1, 7.

Linked-list-based queue

All steps as text
  1. When a queue is implemented using a linked list, we generally use a double-ended linked list with front and rear references. The front points to the first item of the queue and the rear points to the last item.
  2. Performing a removal operation on the first element in the list corresponds to executing a dequeue operation.
  3. Adding an element to the end of the list corresponds to inserting an element into the queue (i.e., the enqueue operation).
  4. 5, 0, 1 and 7 are left, 5 at the front and 7 at the rear. Dequeue and enqueue each changed only a couple of links, so both take O(1).
Linked-list-based queue. Last step: 5, 0, 1 and 7 are left, 5 at the front and 7 at the rear. Dequeue and enqueue each changed only a couple of links, so both take O(1).

Each operation changes only a couple of links, so both are O(1), with no capacity limit. An enqueue into an empty queue sets both front and rear, and dequeuing the last node sets both to null.

Note

In C and C++ a link is a pointer; in Java and Python it is a reference. In C++ a dequeued node must also be freed with delete.

Queue overflow and underflow

Queue overflow is an enqueue onto a full queue. Only a bounded queue, such as a static circular array, can overflow; a queue on a dynamic array or a linked list fails only when memory runs out. Queue underflow is a dequeue or peek on an empty queue.

What is the difference between enqueue and dequeue?

Enqueue adds an item at the rear of the queue; dequeue removes the item at the front, the one that has waited longest, and returns it. Try both on the interactive queue under Queue operations.

What is a circular queue?

It is a queue on a circular array: its indices wrap from the last cell back to the first, so freed cells are reused, and enqueue and dequeue both stay O(1).

Queue time complexity: array vs linked list

OperationStatic circular arrayDynamic circular arrayLinked list
EnqueueO(1); fails when fullO(1) amortized, O(n) worst caseO(1)
DequeueO(1)O(1) amortized, O(n) worst caseO(1)
Peek, isEmpty, sizeO(1)O(1)O(1)
SearchO(n)O(n)O(n)

Search is not a queue operation. Space is O(n); a static array reserves its whole capacity up front. A dynamic circular array allocates nothing per enqueue but copies everything when it resizes. A linked list never copies, but every enqueue allocates a node with an extra link.

Queue vs stack

A queue and a stack differ only in which item leaves: a stack removes the newest, a queue the oldest. So breadth-first search uses a queue, and depth-first search a stack. A queue can also be built from two stacks. Enqueue pushes onto the first; dequeue pops from the second, refilling it from the first only when it is empty. Each item moves across once, so both are O(1) amortized.

Types of queue: circular, double-ended, priority

  • Simple (linear) queue: enqueue at the rear, dequeue at the front.
  • Circular queue: a simple queue on a circular buffer.
  • Deque (double-ended queue): adds and removes at both ends, so it can act as a stack or as a queue.
  • Priority queue: removes the item with the highest priority, not the oldest, so it is not FIFO. It is usually built on a heap, such as a min-heap.
  • Blocking queue: a thread-safe queue; consumers wait while it is empty and, if it is bounded, producers wait while it is full.

Queues in Python, Java and C++

In Python, list.pop(0) shifts every remaining item, so collections.deque is used instead: append(), popleft() and d[0] all take O(1). popleft() on an empty deque raises IndexError. queue.Queue is thread-safe, and its get() blocks while it is empty. In Java, Queue is an interface. ArrayDeque, a growable circular array, is usually faster than LinkedList as a queue, and it rejects null. add, remove and element throw on failure, while offer, poll and peek return false or null. C++'s std::queue is an adaptor over std::deque by default, with push(), pop(), front() and back(). pop() returns nothing, so read front() first; on an empty queue, both are undefined behavior.

The full source code is on GitHub, in Python, Java and C++.

Where queues are used: applications of a queue

  • Print spooling, web servers, and task and message queues: work is served in the order it arrives.
  • Breadth-first search of a graph and level-order traversal of a tree: nodes found first are visited first.
  • Buffers for keyboard input, network packets and video streaming: data is used in the order it was produced.
  • Round-robin CPU scheduling: a process that uses up its time slice goes to the back of the queue.

Queue interview problems include a queue from two stacks, design circular queue and sliding-window maximum with a deque.

Three animations here.
The whole topic in the app.

In VisiGrab the queue is an 18-slide show, from an enqueue/dequeue demo to the linked-list-based queue, played one step at a time.

Enqueue / dequeue demo

A six-slot queue holding 7, 4, 2 and 0 next to the FIFO definition. Enq adds a random number at the rear and Deq removes the front, and each button switches off when the queue is full or empty.

Interactive circular array

An array of six cells holding 8, 3, 5 and 0, with front and rear markers that wrap round as you press Enq and Deq. A help dialog explains the circular array and the modulo rule, with the index update in your chosen language.

Forward and back

Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.

Theory and complexity

Two tabs: Info, with the key characteristics of a queue as an abstract data type, and Efficiency, with a complexity table for a linked list, a static array and a dynamic array.

Python, Java and C++

Four queues in each language: on a static circular array (a bounded array in Python), on a dynamic array that doubles and halves, on an ArrayList, list or vector whose dequeue is O(n), and on a linked list. Notes on thrashing and memory sit between the listings, with links to the full source on GitHub.

Quiz

Ten questions to check what you have learned before moving on.

Build a queue
enqueue by enqueue.

Download VisiGrab and step through the printer queue, the web server and the linked-list-based queue, then try the circular array yourself.

The queue is one of 30+ topics. See them all