AlgoScope

Stack vs Queue

Data StructuresData structurebeginner

Stack and Queue are both data structures. Play them side by side below, then see exactly where they diverge.

Either player can stop before each decision and ask what happens next: turn on Predict mode in its top bar.

Only the top is reachable. The last thing down is the first thing up.

Push 9. 9 is now the top item. The stack has 3 items.539bottomtoptop
push 9 and it lands on top. Size 3.

Items drop onto the TOP and lift off the TOP. Nothing below moves.

You join at the back and leave from the front, like a queue at a counter.

Enqueue 9 at the rear. The queue has 3 items. The front is 5.539frontrearfrontrear
enqueue 9 and it joins at the rear. Size 3.

FRONT -> items -> REAR. Enqueue slides in at the rear, dequeue leaves from the front.

How they differ

Both add and remove in O(1). What separates them is which end things leave from. A stack hands back the last thing put in - only the top is reachable - while a queue hands back the first: you join at the back and leave from the front. The same difference separates depth-first search, whose frontier is a stack, from breadth-first search, whose frontier is a queue.

The run shown here takes 10 steps for Stack and 10 steps for Queue. That count moves with the input - use the example tabs above either player to see it change.

What each operation costs, for Stack and Queue side by side.
CostStackQueue
peekO(1)O(1)
searchO(n)O(n)
pushO(1)not documented
popO(1)not documented
enqueuenot documentedO(1)
dequeuenot documentedO(1)
spaceO(n)O(n)

A dash means the curriculum entry for that topic documents no cost under that name. It is not a claim that the operation is impossible: push on a stack and enqueue on a queue are written as different operations, so they are listed as different rows rather than paired up here.