A queue is a linear data structure that follows the First-In, First-Out (FIFO) principle: the earliest inserted element is the first one removed. Think of a line at a ticket counter—people are served in the order they arrive.
Queues maintain two conceptual ends: a front from which elements are removed, and a rear to which new elements are added. This ordering naturally supports workflows where tasks arrive over time and must be processed in arrival order.
// Interface
Queue:
enqueue(x)
y = dequeue()
y = front()
b = isEmpty()
n = size()
// Breadth-First Search using a queue
function BFS(graph, start):
q ← new Queue()
visited ← empty set
enqueue(q, start)
add start to visited
while not isEmpty(q):
v ← dequeue(q)
for each u in graph.neighbors(v):
if u not in visited:
add u to visited
enqueue(q, u)
Stacks are LIFO (last-in, first-out) and support backtracking and function call management; queues are FIFO and support fair scheduling and level-wise processing. Many systems use both, each where its ordering semantics best fit the problem.