Arrays store data by position; linked structures store data by reference — each node points to the next. That trade-off (cheap insertion, no random access) gives us linked lists, and the stack and queue that so many algorithms rely on.
Linked lists
A singly linked list is a chain of nodes, each holding a value and a pointer to the next. Inserting at the front is O(1) (no shifting), but reaching the k-th element means walking the chain — O(n):
class Node:def __init__(self, val, next=None):self.val = valself.next = next# Build 1 → 2 → 3head = Node(1, Node(2, Node(3)))# Traversenode = headwhile node:print(node.val)node = node.next
The classic exercise — reverse a linked list — is worth memorising, as it teaches pointer manipulation:
def reverse(head):prev = Nonewhile head:nxt = head.next # save nexthead.next = prev # flip the pointerprev = head # advancehead = nxtreturn prev # new head
Stacks (LIFO)
A stack is last-in, first-out — like a stack of plates. Push and pop from one end, both O(1). A plain list works as a stack:
def is_balanced(s):pairs = {")": "(", "]": "[", "}": "{"}stack = []for ch in s:if ch in "([{":stack.append(ch)elif ch in pairs:if not stack or stack.pop() != pairs[ch]:return Falsereturn not stack
Queues (FIFO)
A queue is first-in, first-out — like a line at a counter. Add at the back, remove from the front. Use collections.deque for O(1) at both ends (a list's pop(0) is O(n)):
from collections import dequeq = deque()q.append("a") # enqueue at the backq.append("b")q.popleft() # "a" — dequeue from the front
When to use which
- Stack — undo/redo, matching brackets, depth-first traversal, function call frames.
- Queue — task scheduling, breadth-first traversal, buffering.
- Linked list — when you insert/remove at the ends constantly and never need random access.
Practice
Implement: (1) reverse a linked list; (2) check if a string of brackets is balanced using a stack; (3) a simple queue with deque. These three appear constantly in interviews.
Key takeaways
- 01Linked lists trade O(1) end-insertion for O(n) random access — nodes point to the next.
- 02Reversing a linked list in place is a must-know pointer exercise.
- 03A stack is LIFO (push/pop one end) — brackets, undo, depth-first search.
- 04A queue is FIFO — use collections.deque for O(1) at both ends.
- 05Pick the structure by access pattern: ends-only + no indexing → linked/stack/queue.
