Both hold items in order and let you add and remove them. The difference is which end you remove from: a stack removes the item you added last (a pile of plates); a queue removes the item you added first (a line at a counter).
The comparison table
| Stack | Queue | |
|---|---|---|
| Order | LIFO — last in, first out | FIFO — first in, first out |
| Insert | push, at the top | enqueue, at the rear |
| Remove | pop, from the top | dequeue, from the front |
| Peek | top | front |
| Ends used | One (top) | Two (front and rear) |
| Real-life picture | Plates, browser Back button, undo | Ticket line, print jobs, keyboard buffer |
| Uses in CS | Function calls, recursion, expression evaluation, bracket matching, DFS | Scheduling, BFS, buffering, producer–consumer |
Stack in Python
stack = []
stack.append(10) # push
stack.append(20)
stack.append(30)
top = stack[-1] # peek → 30
x = stack.pop() # pop → 30
print(stack) # [10, 20]
Underflow check: if not stack: print("Underflow") before popping.
Queue in Python
from collections import deque
q = deque()
q.append("A") # enqueue
q.append("B")
q.append("C")
front = q[0] # peek → "A"
y = q.popleft() # dequeue → "A"
print(q) # deque(['B', 'C'])
A plain list works but pop(0) shifts every element (O(n)); deque.popleft() is O(1).
Worked example — bracket matching with a stack
Check whether {[()]} is balanced: push each opening bracket; on a closing bracket, pop and check it matches; at the end the stack must be empty.
def balanced(s):
pairs = {')': '(', ']': '[', '}': '{'}
st = []
for ch in s:
if ch in '([{':
st.append(ch)
elif ch in ')]}':
if not st or st.pop() != pairs[ch]:
return False
return not st
balanced("{[()]}") → True; balanced("([)]") → False.
Worked example — a queue trace
Start empty. enqueue 5, enqueue 8, dequeue, enqueue 2, dequeue, dequeue.
| Step | Queue (front → rear) | Removed |
|---|---|---|
| enqueue 5 | 5 | |
| enqueue 8 | 5 8 | |
| dequeue | 8 | 5 |
| enqueue 2 | 8 2 | |
| dequeue | 2 | 8 |
| dequeue | (empty) | 2 |
The same trace on a stack (push 5, push 8, pop, push 2, pop, pop) removes 8, then 2, then 5.
Variants worth knowing
- Circular queue — the rear wraps round to reuse freed space in a fixed array.
- Deque — insert and remove at both ends.
- Priority queue — removal by priority rather than arrival (usually a heap).
How it is tested
- "Write the difference between a stack and a queue" — LIFO/FIFO and the operations, as a table.
- Trace questions: give the contents after a sequence of pushes/pops or enqueues/dequeues.
- "Convert infix to postfix" and "evaluate a postfix expression" — stack, Class 12 favourites.
- "Implement a queue using two stacks" — GATE and interviews: push to stack A; to dequeue, pour A into B when B is empty and pop from B.