Queues
↑At a glance
Section titled “At a glance”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 the operations
Section titled “Try the operations”Try it yourself
First in, first out (FIFO)
New values enter at the back and the oldest value leaves at the front.
How the order works
Section titled “How the order works”- Add items one after another.
- Look at the next item. It is the value that entered earliest.
- Remove one item. The next item changes, but the remaining order is preserved.
- Repeat until the collection is empty.
var items = new Queue<int>();items.Enqueue(10);items.Enqueue(20);Console.WriteLine(items.Peek()); // 10Console.WriteLine(items.Dequeue()); // 10#include <queue>#include <iostream>std::queue<int> items;items.push(10);items.push(20);std::cout << items.front() << '\n'; // 10items.pop(); // pop returns void in C++When does this help?
Section titled “When does this help?”Queues fit scheduling, producer-consumer pipelines, event processing and breadth-first search. They preserve arrival order.
What FIFO guarantees
Section titled “What FIFO guarantees”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.
Where queues help
Section titled “Where queues help”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.
Cost and implementation
Section titled “Cost and implementation”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.
