Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.py
from collections import deque
queue = deque()
for value in [10, 20, 30]:
queue.append(value)
removed = []
while queue:
removed.append(queue.popleft())
print(" -> ".join(str(x) for x in removed))
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- Python uses
collections.dequefor the queue, not a list withpop(0).queue.append(value)mutates the right end, andqueue.popleft()removes and returns the oldest value from the left in O(1) time. - The deque and the
removedlist are separate containers. Eachremoved.append(queue.popleft())transfers the returnedintreference intoremovedwhile shrinking the deque. - The visible containers are the deque and the
removedlist; normal Python GC owns them once no references remain. The trace shows the queue move from[]to[10, 20, 30], then drain intoremoved.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.