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.