Queue — Explained with Examples
A queue is a FIFO (First-In-First-Out) data structure where elements are added at the rear and removed from the front, like a waiting line.
Queues support enqueue (add to rear) and dequeue (remove from front) operations, both O(1) with proper implementations. Variants include circular queues (reuses array slots), double-ended queues (deque) (insert/remove at both ends), and priority queues (elements removed by priority). BFS uses a queue for level-order traversal.
Think of a queue like a line at a coffee shop. The first person to arrive gets served first. New arrivals join at the back. No cutting in line — that would violate the FIFO principle that makes queues fair and predictable.
Queues are used in breadth-first search, print spooling, task scheduling, message queues (RabbitMQ, Kafka), and buffering data streams.
from collections import deque
class Queue:
def __init__(self):
self.items = deque()
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.popleft()
raise IndexError("dequeue from empty queue")
def front(self):
if not self.is_empty():
return self.items[0]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Breadth-First Search using queue
def bfs_shortest_path(graph, start, goal):
queue = Queue()
queue.enqueue([start])
visited = {start}
while not queue.is_empty():
path = queue.dequeue()
node = path[-1]
if node == goal:
return path
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
new_path = list(path)
new_path.append(neighbor)
queue.enqueue(new_path)
return None
graph = {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C']}
print(bfs_shortest_path(graph, 'A', 'D')) # ['A', 'B', 'D'] or ['A', 'C', 'D']Queues are the backbone of asynchronous systems. In task scheduling, jobs wait in a queue until a worker is available to process them.
Stack, Linked List, BFS, Priority Queue
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro