Data structures

Stacks and queues, visualized.

Two linked lists with rules. A stack only touches the top; a queue adds at the back and takes from the front. Push, pop and enqueue them yourself, then use a stack to check brackets.

What are stacks and queues?

A stack is a list you only touch at one end, the top: push puts an item on top and pop takes the top item off. The last item in is the first out (LIFO).

A queue adds at the back and removes from the front, like a line at a till: the first item in is the first out (FIFO). Both are a linked list with fewer doors, which is why every operation costs O(1).

01 — one item first

Start with one push.

A stack is the linked list from the last lesson, with one rule: you only ever touch the head. Here it is called top.

handed back:

Python

class Stack:
def __init__(self):
self.top = None
def push(self, value):
node = Node(value)
node.next = self.top
self.top = node
def pop(self):
node = self.top
self.top = node.next
return node.value
def peek(self):
return self.top.value

02 — same input, different rule

Stack vs queue.

Put the same four numbers into both, then take everything out. One hands them back reversed, the other keeps the line.

Stack

push to the top, pop from the top

out:

Queue

enqueue at the back, dequeue from the front

out:

Press the button to put in 1, 2, 3, 4.

03 — the second pointer

Why a queue keeps a tail.

A stack needs one pointer. A queue works at both ends, so it keeps two: head for the front and tail for the back. Watch what the tail saves.

The queue holds 4, 8, 15, 16. Add 23 at the back, two ways.

04 — your turn

Push, pop, enqueue, dequeue.

Switch between a stack and a queue. Every button runs the class on the right, line by line.

handed back:

Pick a value and press a button.

Python

class Stack:
def __init__(self):
self.top = None
def push(self, value):
node = Node(value)
node.next = self.top
self.top = node
def pop(self):
node = self.top
self.top = node.next
return node.value
def peek(self):
return self.top.value
Each operation ends with its cost here.

05 — the classic bug

The queue that forgot its tail.

When dequeue takes the last item, the queue is empty and tail must go back to None too. Skip that one line and the next enqueue vanishes.

handed back:

The queue holds just 7. We will dequeue(), then enqueue(5).

Buggy

node = self.head
self.head = node.next
return node.value # tail still points at node

Fixed

node = self.head
self.head = node.next
if self.head is None:
self.tail = None # empty again
return node.value

06 — spot them in the wild

Stack or queue? Real examples.

Both are everywhere once you look. Pick one for each, then read why.

The browser Back button

A printer with five jobs waiting

Undo in a text editor

Customer support tickets

Function calls waiting to return

Breadth-first search through a maze

07 — the boss level

Valid parentheses with a stack.

A classic interview question, and the stack’s best trick: every opener waits on the stack until its closer arrives. If the top is the wrong opener, the string is broken.

Python

def is_valid(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in '([{':
stack.append(ch) # opener: push
elif not stack or stack.pop() != pairs[ch]:
return False # wrong closer
return not stack # leftovers fail
Time O(n): one look per character. Memory O(n): in the worst case every character is an opener.

08 — cheat sheet

Stack and queue time complexity.

Every operation is O(1), as long as you pick the right tool in your language.

JobCostIn Python
Stack: push, pop, peekO(1)list.append, list.pop(), stack[-1]
Queue: enqueue, dequeueO(1)with a tail pointerdeque.append, deque.popleft()
Queue without a tailO(n) enqueuewalk to the back every time
Queue on a plain listO(n) dequeuelist.pop(0) shifts every itemuse collections.deque; see deque vs list
Search for a valueO(n)neither is built for it

09 — take it with you

Stack and queue in Python: the full code.

Both classes and the bracket checker in one file. In everyday Python, reach for list as a stack and collections.deque as a queue; these show what they do inside.

stacks_and_queues.py

class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.top = None
def push(self, value):
node = Node(value)
node.next = self.top
self.top = node
def pop(self):
node = self.top
self.top = node.next
return node.value
def peek(self):
return self.top.value
class Queue:
def __init__(self):
self.head = self.tail = None
def enqueue(self, value):
node = Node(value)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
node = self.head
self.head = node.next
if self.head is None:
self.tail = None # empty again
return node.value
def is_valid(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in '([{':
stack.append(ch) # opener: push
elif not stack or stack.pop() != pairs[ch]:
return False # wrong closer
return not stack # leftovers fail
Back to the startLinked listUp nextHash map