Skip to content

Queues

↑
Data structures

A queue is first in, first out (FIFO). The oldest item is removed first, like a line of people waiting.

Action Meaning Typical time
Enqueue Add an item O(1) amortized
Dequeue Remove the front item O(1)
Peek Inspect the next item without removing it O(1)

Try it yourself

First in, first out (FIFO)

New values enter at the back and the oldest value leaves at the front.

  1. Add items one after another.
  2. Look at the next item. It is the value that entered earliest.
  3. Remove one item. The next item changes, but the remaining order is preserved.
  4. Repeat until the collection is empty.
C# | QueueExample.cs
var items = new Queue<int>();
items.Enqueue(10);
items.Enqueue(20);
Console.WriteLine(items.Peek()); // 10
Console.WriteLine(items.Dequeue()); // 10

Queues fit scheduling, producer-consumer pipelines, event processing and breadth-first search. They preserve arrival order.

A queue removes the element that has waited longest: first in, first out. FIFO describes the order of entry and removal, not priority, completion time or fairness in a distributed system. If some jobs need to jump ahead, you probably need a priority queue or a scheduler rather than a basic queue.

Breadth-first search, task dispatch, event processing and message buffering often use queues. They are particularly helpful when producers and consumers work at different rates, but a queue does not eliminate overload. You still need a limit, backpressure policy or retry strategy.

A queue implemented with a linked list or circular buffer can enqueue and dequeue in constant time. Removing the first element of a general array list may instead require shifting every other item. Choose the data structure that matches the operations you actually need.