Queue<T> · C#
Enqueue
Adds an element at the back.
public void Enqueue(T item)
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(1) |
| Worst case | O(n) when the buffer is full |
| Extra space | O(1) amortized |
Write at the tail index and advance it modulo the capacity. A full buffer doubles and copies the elements in order, which amortizes to O(1).
Tested example
var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
Assert.Equal(2, queue.Count);
Assert.Equal(["first", "second"], queue); // enumerates front to back
Parameters
- item
- The element.
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- None.
- Changes
- Count increases by 1; may replace the buffer.
- Memory and invalidation
- Growth allocates a new array and unwraps the ring into it.