π Stack LIFO
Last In, First Out β like a stack of plates. Push adds to top, pop removes from top.
Visual
β² TOP
[ empty stack ]Push items to see them stack up β
βΌ BOTTOM
Operations
Push an item to begin.
Operation Log
Operations appear hereβ¦
πΆ Queue FIFO
First In, First Out β like a real queue. Enqueue adds to rear, dequeue removes from front.
Operations
Enqueue an item to begin.
Quick Reference
Stack (LIFO):
push(x) β O(1) pop() β O(1)
peek() β O(1) is_empty() β O(1)
Queue (FIFO):
enqueue(x) β O(1) dequeue() β O(1)
front() β O(1) is_empty() β O(1)
π Stack vs Queue β Head-to-Head Comparison
π Stack (LIFO)
OrderLast In, First Out
Addpush() β top
Removepop() β top
Peekpeek() / top()
Pythonlist.append/pop
SpaceO(n)
Time opsO(1) all
πΆ Queue (FIFO)
OrderFirst In, First Out
Addenqueue() β rear
Removedequeue() β front
Peekfront()
Pythoncollections.deque
SpaceO(n)
Time opsO(1) all
π» Python Code Examples
# Stack using list
stack = []
stack.append(10) # push
stack.append(20)
stack.append(30)
print(stack.pop()) # 30 β LIFO
print(stack[-1]) # peek β 20
# Queue using deque
from collections import deque
q = deque()
q.append(10) # enqueue (rear)
q.append(20)
q.append(30)
print(q.popleft()) # 10 β FIFO
print(q[0]) # front β 20
π Real-World Use Cases
π
Browser Back Button
Stack β each page visited is pushed; back button pops
π¨οΈ
Print Queue
Queue β first document sent is printed first (FIFO)
β©οΈ
Undo Feature
Stack β each action pushed; Ctrl+Z pops last action
π₯οΈ
CPU Scheduling
Queue β processes handled in order they arrive (FIFO)
π
Call Center
Queue β first caller on hold is first to be answered
π§
DFS Algorithm
Stack β depth-first search explores deepest path first
πΊοΈ
BFS Algorithm
Queue β breadth-first explores level by level outward
β
Bracket Checker
Stack β push opening, pop and match when closing found