Programming Search⌘K

Conceptintro

Queue

Also called queue, FIFO, first in first out, enqueue, dequeue, FIFO queue, Queue<T>, std::queue, blocking queue.

A queue is a collection that gives back its items in the order they arrived: the first item in is the first item out. Programs use queues for work that waits its turn.

Applies to
core-languages

Idea

A queue is a line of items that wait their turn. Wikipedia: "The name queue is an analogy to the words used to describe people in line to wait for goods or services."1 New items join at the back, and the program takes items from the front. "The operations of a queue make it a first-in-first-out (FIFO) data structure as the first element added to the queue is the first one removed."1

from collections import deque

jobs = deque()
for name in ["print report", "send mail", "resize image"]:
    jobs.append(name)
    print("enqueue", name, "waiting", len(jobs))

while jobs:
    print("run", jobs.popleft(), "waiting", len(jobs))
Output
enqueue print report waiting 1
enqueue send mail waiting 2
enqueue resize image waiting 3
run print report waiting 2
run send mail waiting 1
run resize image waiting 0

How it works

Operations. A queue has two main operations.1

  • enqueue "adds one element to the rear of the queue";
  • dequeue "removes one element from the front of the queue".

Many queues also have a peek or front operation, which returns the next item and does not remove it.1 A dequeue on an empty queue is an underflow. A queue with a fixed size is a bounded queue, and an enqueue on a full bounded queue fails or waits.1

Implementations. A queue changes at both ends, so a plain array is a poor fit: a removal at the front moves every other item. Wikipedia names the usual choices: "A queue may be implemented as circular buffers and linked lists".1

  • A ring buffer keeps the items in an array, with an index for the front and a count. Both indexes wrap around at the end of the array. See Ring buffer.
  • A linked list adds at the tail and removes at the head. See linked-list.
  • Two stacks also make a queue. One stack takes new items. When the other stack is empty, the program moves all items across, which reverses their order. Wikipedia describes this purely functional queue: "the amortized time is O(1), but individual operations can take O(n)".1

Where programs use queues. A queue holds work that arrives faster than the program can do it: print jobs, network messages, events in a user interface, and the nodes to visit in a breadth-first walk of a graph. A queue that threads share is a channel between producers and consumers. See channels and worker-queue.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptIdiom
TypeScriptIdiomTypeScript has no queue type. A program uses an array with push and shift, or a class with an array and a head index, as in JavaScript. No example file exists.
GoIdiom
RustStandard library
KotlinStandard libraryKotlin has ArrayDeque with addLast and removeFirst, and java.util.ArrayDeque on the JVM. No example file exists because kotlinc is not installed.
SQLIdiomA table of jobs with an order column works as a queue. A consumer reads the row with the smallest order value and deletes it or marks it done.
BashIdiomAn indexed array and a front index work as a queue. Bash has no queue type. No example file exists.
PowerShellStandard library[System.Collections.Generic.Queue[T]] gives the .NET queue with Enqueue, Dequeue and Peek. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. It has no data structures for a program.
CSSDoes not applyCSS style rules have no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.
Language Verdict Form
Python stdlib collections.deque, with append and popleft; queue.Queue between threads234
JavaScript idiom an array with push and shift, or a class around a ring buffer
TypeScript idiom an array, as in JavaScript
Java stdlib the Queue interface, with ArrayDeque or LinkedList56
C idiom a ring buffer in an array, or a linked list
C++ stdlib std::queue, an adaptor over std::deque by default7
C# stdlib Queue<T>, a circular array8
Go idiom a slice, or container/list; a buffered channel between goroutines9
Rust stdlib VecDeque, with push_back and pop_front10
Kotlin stdlib ArrayDeque
PowerShell stdlib [System.Collections.Generic.Queue[T]] from .NET
Bash idiom an indexed array and a front index
SQL idiom a table of jobs with an order column
Regex n/a a pattern has no data structures
HTML/CSS n/a markup and style rules have no data structures

Python. A list can work as a queue, but the tutorial warns that "lists are not efficient for this purpose".2 "While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one)."2 It says: "To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends."2 Deques "support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction".3 For threads, the queue module "implements multi-producer, multi-consumer queues".4 A queue.Queue with a maxsize is bounded: "Insertion will block once this size has been reached, until queue items are consumed."4

Java. The Queue interface has two forms of each operation: "one throws an exception if the operation fails, the other returns a special value (either null or false , depending on the operation)".5 So add, remove and element throw, and offer, poll and peek return a value.5 ArrayDeque is "faster than LinkedList when used as a queue".6 Methods that wait "for elements to appear or for space to become available" are in the BlockingQueue interface, which extends Queue.5

C++. "The std::queue class template is a container adaptor that gives the functionality of a queue - specifically, a FIFO (first-in, first-out) data structure."7 It "pushes the elements on the back of the underlying container and pops them from the front".7

C#. Queue<T> "Represents a first-in, first-out collection of objects."8 The remarks say: "This class implements a generic queue as a circular array."8

Rust. VecDeque is "A double-ended queue implemented with a growable ring buffer."10 The usual way to use it as a queue is to "use push_back to add to the queue, and pop_front to remove from the queue".10 pop_front returns None when the deque is empty.10

JavaScript. JavaScript has no queue type. shift removes the first item of an array: it "shifts all values to the left by 1 and decrements the length by 1".11 That costs time in proportion to the length, so a large queue needs a ring buffer or a head index.

Go. Go has no queue type. A slice works for a small queue. Between goroutines, a buffered channel is a queue: "Channels act as first-in-first-out queues."9

The example files enqueue three items, dequeue one, peek at the next one and show what happens on an empty queue.

PythonGitHub
from collections import deque

queue = deque()
for item in ["a", "b", "c"]:
    queue.append(item)
print(list(queue), "front", queue[0])

print(queue.popleft(), "next", queue[0], "size", len(queue))
queue.popleft()
queue.popleft()
print("empty:", "yes" if not queue else "no")

try:
    queue.popleft()
except IndexError as error:
    print("IndexError:", error)
Output
['a', 'b', 'c'] front a
a next b size 2
empty: yes
IndexError: pop from an empty deque
  • Verdict: stdlib. collections.deque is the queue. append adds at the back, popleft removes from the front, and queue[0] peeks.
  • popleft on an empty deque raises IndexError.
  • For a queue between threads, use queue.Queue.
#include <initializer_list>
#include <iostream>
#include <queue>
#include <string>

int main() {
    std::queue<std::string> queue;
    for (const char *item : {"a", "b", "c"}) {
        queue.push(item);
    }
    std::cout << "front " << queue.front() << " back " << queue.back()
              << " size " << queue.size() << '\n';

    // pop returns void, so read front first.
    std::string first = queue.front();
    queue.pop();
    std::cout << first << " next " << queue.front() << " size " << queue.size() << '\n';

    queue.pop();
    queue.pop();
    std::cout << "empty: " << (queue.empty() ? "yes" : "no") << '\n';
}
Output
front a back c size 3
a next b size 2
empty: yes
  • Verdict: stdlib. std::queue is an adaptor over std::deque by default. push adds at the back, and pop removes the front.
  • pop returns nothing, so the program reads front() first. It checks empty() before front or pop.
JavaGitHub
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();
        for (String item : new String[] {"a", "b", "c"}) {
            queue.offer(item);
        }
        System.out.println(queue + " front " + queue.peek());

        String first = queue.poll();
        System.out.println(first + " next " + queue.peek() + " size " + queue.size());
        queue.poll();
        queue.poll();
        System.out.println("empty: " + (queue.isEmpty() ? "yes" : "no"));
        System.out.println("poll on empty: " + queue.poll());
        try {
            queue.remove();
        } catch (NoSuchElementException e) {
            System.out.println("remove on empty: NoSuchElementException");
        }
    }
}
Output
[a, b, c] front a
a next b size 2
empty: yes
poll on empty: null
remove on empty: NoSuchElementException
  • Verdict: stdlib. ArrayDeque through the Queue interface is the queue. offer adds at the tail, poll removes the head, and peek reads it.
  • poll and peek return null on an empty queue. remove and element throw NoSuchElementException.
#include <stdbool.h>
#include <stdio.h>

#define CAPACITY 4

/* A ring buffer: head is the front, count is the number of items. */
struct queue {
    char items[CAPACITY];
    int head;
    int count;
};

static bool enqueue(struct queue *q, char c) {
    if (q->count == CAPACITY) {
        return false;
    }
    q->items[(q->head + q->count) % CAPACITY] = c;
    q->count++;
    return true;
}

static bool dequeue(struct queue *q, char *out) {
    if (q->count == 0) {
        return false;
    }
    *out = q->items[q->head];
    q->head = (q->head + 1) % CAPACITY;
    q->count--;
    return true;
}

int main(void) {
    struct queue q = {.head = 0, .count = 0};
    for (const char *p = "abc"; *p != '\0'; p++) {
        enqueue(&q, *p);
    }
    char c = 0;
    dequeue(&q, &c);
    printf("dequeue %c, front %c, count %d\n", c, q.items[q.head], q.count);

    /* The tail wraps around to the start of the array. */
    enqueue(&q, 'd');
    enqueue(&q, 'e');
    printf("enqueue f: %s\n", enqueue(&q, 'f') ? "yes" : "no");

    const char *sep = "";
    while (dequeue(&q, &c)) {
        printf("%s%c", sep, c);
        sep = " ";
    }
    printf("\ndequeue on empty: %s\n", dequeue(&q, &c) ? "yes" : "no");
    return 0;
}
Output
dequeue a, front b, count 2
enqueue f: no
b c d e
dequeue on empty: no
  • Verdict: idiom. C has no queue type. A fixed array with a head index and a count is a bounded queue, and the indexes wrap with %.
  • The functions return false when the queue is full or empty.
var queue = new Queue<string>();
foreach (var item in new[] { "a", "b", "c" })
{
    queue.Enqueue(item);
}
Console.WriteLine($"{string.Join(",", queue)} front {queue.Peek()}");

Console.WriteLine($"{queue.Dequeue()} next {queue.Peek()} size {queue.Count}");
queue.Dequeue();
queue.Dequeue();
Console.WriteLine($"TryDequeue on empty: {(queue.TryDequeue(out var item2) ? item2 : "no")}");
try
{
    queue.Dequeue();
}
catch (InvalidOperationException)
{
    Console.WriteLine("Dequeue on empty: InvalidOperationException");
}
Output
a,b,c front a
a next b size 2
TryDequeue on empty: no
Dequeue on empty: InvalidOperationException
  • Verdict: stdlib. Queue<T> has Enqueue, Dequeue and Peek, and it enumerates from the front.
  • Dequeue on an empty queue throws InvalidOperationException. TryDequeue returns false instead.
JavaScriptGitHub
// An array with a head index: dequeue does not move the other items.
class Queue {
  #items = [];
  #head = 0;

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

  dequeue() {
    if (this.#head === this.#items.length) {
      return undefined;
    }
    const item = this.#items[this.#head];
    this.#items[this.#head] = undefined;
    this.#head++;
    if (this.#head === this.#items.length) {
      this.#items = [];
      this.#head = 0;
    }
    return item;
  }

  peek() {
    return this.#items[this.#head];
  }

  get size() {
    return this.#items.length - this.#head;
  }
}

const queue = new Queue();
for (const item of ["a", "b", "c"]) {
  queue.enqueue(item);
}
console.log("front", queue.peek(), "size", queue.size);
console.log(queue.dequeue(), "next", queue.peek(), "size", queue.size);
queue.dequeue();
queue.dequeue();
console.log("empty:", queue.size === 0 ? "yes" : "no");
console.log("dequeue on empty:", queue.dequeue());

// shift() also works, but it moves every other item.
const simple = ["a", "b", "c"];
console.log(simple.shift(), simple.join(","));
Output
front a size 3
a next b size 2
empty: yes
dequeue on empty: undefined
a b,c
  • Verdict: idiom. JavaScript has no queue type. A class with an array and a head index dequeues in constant time.
  • shift() is the short form, but it moves every remaining item, so it is slow for a large queue.
package main

import "fmt"

func main() {
	// A slice as a queue: append at the back, slice off the front.
	var queue []string
	for _, item := range []string{"a", "b", "c"} {
		queue = append(queue, item)
	}
	fmt.Println(queue, "front", queue[0])

	first := queue[0]
	queue = queue[1:]
	fmt.Println(first, "next", queue[0], "size", len(queue))
	queue = queue[2:]
	fmt.Println("empty:", map[bool]string{true: "yes", false: "no"}[len(queue) == 0])

	// A buffered channel is a FIFO queue between goroutines.
	jobs := make(chan string, 3)
	go func() {
		for _, job := range []string{"x", "y", "z"} {
			jobs <- job
		}
		close(jobs)
	}()
	for job := range jobs {
		fmt.Print(job, " ")
	}
	fmt.Println("done")
}
Output
[a b c] front a
a next b size 2
empty: yes
x y z done
  • Verdict: idiom. Go has no queue type. A slice works: append adds at the back and queue[1:] drops the front. The old items stay in the backing array until append makes a new one.
  • A buffered channel is a queue between goroutines, and values arrive in the order they were sent.
RustGitHub
use std::collections::VecDeque;

fn main() {
    let mut queue: VecDeque<&str> = VecDeque::new();
    for item in ["a", "b", "c"] {
        queue.push_back(item);
    }
    let front = queue.front();
    println!("{queue:?} front {front:?}");

    let first = queue.pop_front();
    println!("{first:?} next {:?} size {}", queue.front(), queue.len());
    queue.pop_front();
    queue.pop_front();
    println!("pop_front on empty: {:?}", queue.pop_front());
}
Output
["a", "b", "c"] front Some("a")
Some("a") next Some("b") size 2
pop_front on empty: None
  • Verdict: stdlib. VecDeque is the queue. push_back adds at the back, pop_front removes the front, and front peeks.
  • pop_front returns an Option, so an empty queue gives None.
  • Bounded queue. A queue with a fixed capacity. When it is full, an enqueue fails, waits, or drops an item. See Ring buffer.
  • Blocking queue. A queue for threads. A dequeue on an empty queue waits for an item, and an enqueue on a full queue waits for space.4 The details are in the concurrency area.
  • Deque. A queue that works at both ends. See Deque.
  • Priority queue. A queue that gives back the item with the best priority first, not the oldest item. See Priority queue.
  • Stack. The opposite order: last in, first out. See stack-data-structure.
  • Message queue. A queue between programs, often on another machine, that stores messages until a consumer reads them.

Pitfalls

A list as a queue is slow

list.pop(0) in Python and shift() in JavaScript move every other item one place to the left.211 A loop that empties a queue of n items this way does work in proportion to n squared. The example times both ways on the same 50,000 items.

This code runs but gives a wrong answer on purpose.

import time
from collections import deque

n = 50_000

items = list(range(n))
start = time.perf_counter()
while items:
    items.pop(0)
list_time = time.perf_counter() - start

items = deque(range(n))
start = time.perf_counter()
while items:
    items.popleft()
deque_time = time.perf_counter() - start

print("list slower than deque:", "yes" if list_time > deque_time else "no")
Output
list slower than deque: yes

Use collections.deque in Python. In JavaScript, keep a head index and read items[head++], or use a ring buffer.

A null item looks like an empty Java queue

poll and peek return null when the queue is empty. LinkedList accepts null items, so a program cannot tell a null item from an empty queue. The Queue documentation says that "null should not be inserted into a Queue , as null is also used as a special return value by the poll method to indicate that the queue contains no elements".5

This code runs but gives a wrong answer on purpose.

import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add(null);
        queue.add("b");
        String first = queue.poll();
        System.out.println(first == null ? "queue looks empty" : first);
        System.out.println("size " + queue.size());
    }
}
Output
queue looks empty
size 1

ArrayDeque rejects null items, so it avoids the problem.6

Cost

Operation Ring buffer Linked list Array with shift
enqueue amortized constant constant, with one allocation amortized constant
dequeue constant constant linear
peek constant constant constant
memory per item the item, plus spare capacity the item and one or two links the item, plus spare capacity

Library queues in Python, Java, C#, C++ and Rust do enqueue and dequeue in constant or amortized constant time. Wikipedia calls a queue efficient when its implementation "can perform the operations" of enqueue and dequeue in O(1) time.1

History

The word comes from everyday life: a queue of people waits for a service, and the first person in the line is served first.1 Today most standard libraries have a queue type or a deque that serves as one.357810

References

  1. Queue (abstract data type), Wikipedia, the introduction; Queue implementation; Purely functional implementation
  2. The Python Tutorial, 5. Data Structures, 5.1.2 Using Lists as Queues
  3. collections, Container datatypes, Python documentation, deque objects
  4. queue, A synchronized queue class, Python documentation, the introduction; class queue.Queue
  5. Queue (Java SE 27 and JDK 27), the interface description; Summary of Queue methods
  6. ArrayDeque (Java SE 27 and JDK 27), the class description
  7. std::queue, cppreference.com, the introduction
  8. Queue<T> Class, .NET API reference, the summary; Remarks
  9. The Go Programming Language Specification, Channel types
  10. Struct VecDeque, The Rust Standard Library, the description; pop_front
  11. Array.prototype.shift(), MDN Web Docs, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/5Q5PMY/text.yaml