Difference Between Stack and Queue Data Structure
Stacks and Queues are both linear data structures used to store collections of elements, but they differ fundamentally in the order elements are added and removed.
Stack
A Stack follows the LIFO (Last In, First Out) principle. The last element added is the first one to be removed. Core operations are push (insert) and pop (remove) from the same end, called the top.
Queue
A Queue follows the FIFO (First In, First Out) principle. The first element added is the first one to be removed. Core operations are enqueue (insert at rear) and dequeue (remove from front).
Comparison Table
| Aspect | Stack | Queue |
|---|---|---|
| Order | LIFO | FIFO |
| Insertion | push (at top) | enqueue (at rear) |
| Removal | pop (from top) | dequeue (from front) |
| Access point | Single end (top) | Two ends (front & rear) |
| Use cases | Undo/redo, function call stack, expression evaluation | Task scheduling, printer queues, BFS traversal |
# Stack using a Python list
stack = []
stack.append(1) # push
stack.append(2)
stack.pop() # removes 2 (LIFO)
# Queue using collections.deque
from collections import deque
queue = deque()
queue.append(1) # enqueue
queue.append(2)
queue.popleft() # removes 1 (FIFO)
Applications
- Stack: backtracking algorithms, syntax parsing, browser history.
- Queue: CPU task scheduling, handling requests in web servers, breadth-first search.
Tracing the Same Input Through a Stack and a Queue
The quickest way to feel the difference is to feed both structures the same values and watch what comes out. Suppose you insert A, B and C in that order, then remove two items.
| Step | Stack (top on the right) | Queue (front on the left) |
|---|---|---|
| Insert A | [A] | [A] |
| Insert B | [A, B] | [A, B] |
| Insert C | [A, B, C] | [A, B, C] |
| Remove | returns C, leaves [A, B] | returns A, leaves [B, C] |
| Remove | returns B, leaves [A] | returns B, leaves [C] |
The stack hands values back in reverse order, while the queue preserves the original arrival order. Whenever a problem says "most recent first", think stack. When it says "in the order received" or "fair turn-taking", think queue.
Peek, Empty Checks and Underflow
Both structures usually offer a peek operation that looks at the next item without removing it. For a stack that is the top element; for a queue it is the front element. Calling pop or dequeue on an empty structure is called underflow, and most interview solutions guard against it with an empty check first.
stack = [10, 20]
top = stack[-1] if stack else None # peek at the stack -> 20
from collections import deque
queue = deque([10, 20])
front = queue[0] if queue else None # peek at the queue -> 10
if not stack:
print("Stack underflow")
Building a Queue From Two Stacks
A popular interview question asks you to create a queue using only stack operations. The trick is to keep one stack for incoming items and a second one for outgoing items. When the outgoing stack is empty, you pour everything from the incoming stack into it, which reverses the order and puts the oldest item on top.
class QueueWithStacks:
def __init__(self):
self.inbox = []
self.outbox = []
def enqueue(self, x):
self.inbox.append(x)
def dequeue(self):
if not self.outbox:
while self.inbox:
self.outbox.append(self.inbox.pop())
if not self.outbox:
raise IndexError("queue is empty")
return self.outbox.pop()
Each element moves between the two stacks at most once, so the average (amortised) cost of a dequeue is still constant time.
Mistakes Beginners Make When Choosing
- Using
list.pop(0)as a queue. Removing from the start of a Python list shifts every remaining element, so it becomes slow on large inputs. Usedeque.popleft()instead. - Confusing a queue with a priority queue. A priority queue removes the smallest or most important item, not the oldest. Python offers
heapqfor that. - Using recursion when the input is very deep. Recursion relies on the call stack, which has a limit. An explicit stack in a loop avoids recursion depth errors.
- Forgetting the empty case. Always check before popping, especially in parsing and BFS code.
Quick decision checklist
- Do you need to undo, backtrack or match brackets? Choose a stack.
- Do you need to process items fairly in arrival order or explore level by level? Choose a queue.
- Do you need removal from both ends? Look at a deque.
- Do you need removal by importance? Look at a heap-based priority queue.