Introduction to Stacks and Queues - aloalgo.com

Introduction to Stacks and Queues

Stacks and queues are two fundamental data structures that control the order in which elements are added and removed. The key difference is which element gets removed first.

Stacks (LIFO)

A stack is a Last-In-First-Out (LIFO) data structure. Think of a stack of plates: you can only add or remove from the top. The last item you put on is the first one you take off.

Stack Operations

A stack supports three main operations, all in O(1) time:
  • Push: Add an element to the top
  • Pop: Remove and return the top element
  • Peek: View the top element without removing it

Queues (FIFO)

A queue is a First-In-First-Out (FIFO) data structure. Think of a line at a store: the first person in line is the first one served. Items are added at the back and removed from the front.

Queue Operations

A queue supports three main operations:
  • Enqueue: Add an element to the back
  • Dequeue: Remove and return the front element
  • Peek: View the front element without removing it

Why Use deque Instead of list?

Python lists support append() in O(1), but pop(0) is O(n) because all elements must shift. The deque (double-ended queue) supports O(1) operations on both ends.

Stack vs Queue

AspectStackQueue
OrderLIFO (Last-In-First-Out)FIFO (First-In-First-Out)
AddPush to topEnqueue to back
RemovePop from topDequeue from front
Pythonlistcollections.deque
Real-world analogyStack of platesLine at a store

Time Complexity

OperationStack (list)Queue (deque)
Add elementO(1)O(1)
Remove elementO(1)O(1)
PeekO(1)O(1)
SizeO(1)O(1)
Was this helpful?
© 2026 aloalgo.com. All rights reserved.