Queue
A queue is a collection that gives back the oldest element first: first in, first out (FIFO). You should use a queue whenever elements have to be handled in the order they arrive.
Time and space complexity
| operation | time |
|---|---|
| add an element to the back | amortised |
| remove the front element | amortised |
| read the front element |
Implementation
A normal array cannot provide these operations with the same time complexity, because removing its first element shifts every other element. Here is one of the possible implementations with constant time complexity.
Head index
The queue keeps its elements in a dynamic array and the index of its front element, called head.
Enqueue appends the value to the end of the array.
Dequeue returns the element at index head and moves head forward by one instead of removing the element, so nothing shifts.
Compacting
The slots before head are never used again, but they still take memory.
So when head passes half of the array, it is worth migrating all the elements from head into a new array, reset head to zero and drop the old array.
This takes time, but it happens only after about n / 2 dequeues. That is why we say dequeue is amortised.
Build it
Implement enqueue, dequeue and peek in the class below.
Call compact from dequeue when head passes half of the array.