Linked Lists
Nodes, pointers, and the cost of lookup
A complete, practical guide to linked lists in Python β how to build them from scratch with classes, how traversal and insertion actually work, and why they trade random access for cheap insertion.
class Node: def __init__(self, value, next=None): self.value = value self.next = next head = Node(1, Node(2, Node(3))) node = head while node: print(node.value) node = node.next
1
2
3
βοΈ Why Linked Lists Exist
Arrays are fast to index and slow to insert β linked lists flip that
The Core Trade-Off
A Python list is a contiguous array. Getting the item at index i is a single
arithmetic step and a memory read, so it's O(1). But inserting at the front requires shifting
every existing element one slot to the right, which is O(n). That's the trade: fast access, expensive insertion.
A linked list inverts it. Each element is a separate node holding a
value and a pointer to the next node. There is no contiguous block, so there is no shifting β
inserting at the front is just a couple of pointer assignments, O(1). But finding the item at
index i means walking from the head through i pointers, which is O(n).
That's the trade: expensive access, cheap insertion.
In everyday Python you'll almost always reach for a list or a deque. Linked lists matter when you're building other structures on top of them β stacks, queues, hash tables with chaining, LRU caches, and graph adjacency lists all rely on the same node-and-pointer idea. Learning to build one is learning the vocabulary.
Python has no built-in linked list
The closest standard option is collections.deque, which is implemented as a doubly-linked list of blocks internally. Building one from scratch with classes is the clearest way to understand the mechanics.
- βDefine a
Nodeclass with a value and a next pointer - βTraverse a list from head to tail
- βInsert and delete at the head, tail, and middle
- βBuild a doubly-linked list with
prevandnext - βReverse a singly-linked list in O(n) time and O(1) space
- βRecognise the classic pitfalls β lost pointers and infinite loops
π΅ The Node β The Only Building Block
One class, two attributes
A node holds one value and one reference to the next node. That's the whole idea. A linked list is just a chain of these, with a head variable pointing to the first one and the last node's next set to None.
class Node: def __init__(self, value, next=None): self.value = value self.next = next def __repr__(self): return f"Node({self.value!r})" n1 = Node("a") n2 = Node("b") n3 = Node("c") n1.next = n2 n2.next = n3 print(n1) # Node('a') print(n1.next) # Node('b') print(n1.next.next) # Node('c') print(n1.next.next.next) # None
next is None. That None is what signals the end of the list. Every traversal loop terminates when it hits it, which is why None is sometimes called the list's "sentinel".
A picture of the chain
head β βΌ ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ β value: a β next βββββΌββββΆβ value: b β next βββββΌββββΆβ value: c β next:Noneβ ββββββββββββ΄βββββββββββ ββββββββββββ΄βββββββββββ ββββββββββββ΄βββββββββββ
Each box is a separate object in memory. The arrows are references β Python is following them automatically whenever you write node.next.
Traversal
class Node: def __init__(self, value, next=None): self.value = value self.next = next head = Node(1, Node(2, Node(3, Node(4)))) def to_list(head): result = [] node = head while node is not None: result.append(node.value) node = node.next return result print(to_list(head)) # [1, 2, 3, 4] # Count nodes def length(head): count = 0 node = head while node: count += 1 node = node.next return count print(length(head)) # 4
The traversal pattern is always the same: start with a pointer at the head, do something with the current node, then move the pointer forward. The loop stops when the pointer becomes None.
β‘οΈ A Singly-Linked List Class
Wrap the nodes in a list object
A LinkedList class holds a reference to the head node and provides methods for the common operations. This is the standard way to package the mechanics into something usable.
class Node: def __init__(self, value, next=None): self.value = value self.next = next class LinkedList: def __init__(self): self.head = None self._size = 0 def append(self, value): new = Node(value) if self.head is None: self.head = new else: node = self.head while node.next: node = node.next node.next = new self._size += 1 def prepend(self, value): self.head = Node(value, self.head) self._size += 1 def to_list(self): result = [] node = self.head while node: result.append(node.value) node = node.next return result def __len__(self): return self._size def __iter__(self): node = self.head while node: yield node.value node = node.next ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.prepend(0) print(ll.to_list()) # [0, 1, 2, 3] print(len(ll)) # 4 print(list(ll)) # [0, 1, 2, 3]
prepend() is O(1) β it just creates a node and points it at the current head. append() is O(n) β it has to walk to the end of the list first. That asymmetry is the point of a linked list: cheap at the head, expensive at the tail, unless you store a tail reference.
Adding a tail reference for O(1) append
class LinkedList: def __init__(self): self.head = None self.tail = None # remember the last node self._size = 0 def append(self, value): new = Node(value) if self.head is None: self.head = self.tail = new else: self.tail.next = new self.tail = new self._size += 1 # Now append is O(1) instead of O(n)
A tail pointer is one of the most common optimizations to a linked list. It turns append() from O(n) to O(1), at the cost of one extra reference and a bit of bookkeeping when you delete the last node.
βοΈ Insertion, Deletion, and Search
Pointer surgery β the tricky part
Insertion and deletion are all about the pointers around the target. Get those right and the node drops in or out cleanly; get them wrong and you either lose the rest of the list or create a cycle.
Insert at the head β O(1)
def prepend(self, value): new = Node(value, self.head) # new points at old head self.head = new # head now points at new self._size += 1 # Before: head -> A -> B -> None # After: head -> X -> A -> B -> None
Insert after a specific node β O(1) once you have the node
def insert_after(self, target, value): if target is None: raise ValueError("target node is None") new = Node(value, target.next) # new points at target's successor target.next = new # target now points at new self._size += 1 # Before: A -> B -> C # target = B # After: A -> B -> X -> C
new.next to target.next before you reassign target.next. If you reverse the two lines, target.next is already pointing at the new node, and you've lost the rest of the list.Delete a node by value β O(n)
def delete(self, value): if self.head is None: return False if self.head.value == value: self.head = self.head.next self._size -= 1 return True prev = self.head node = self.head.next while node: if node.value == value: prev.next = node.next self._size -= 1 return True prev = node node = node.next return False # Need to track the PREVIOUS node so it can skip over the target.
Deleting a node means making its predecessor point at its successor. That's why you need two pointers: prev and node.
Search β O(n)
def find(self, value): node = self.head index = 0 while node: if node.value == value: return index, node node = node.next index += 1 return -1, None # Returns (index, node) so callers can chain into insert_after().
There's no shortcut to finding a value in a linked list β every lookup is a full scan. That's the cost of giving up contiguous memory.
The two classic pointer bugs
| Bug | Symptom | Fix |
|---|---|---|
Reassigning next before reading it | Lost tail of the list | Save the next pointer in a variable first |
| Creating a cycle by accident | Traversal never ends | Check pointer assignment order; use id() to debug |
If a traversal hangs, add a counter that aborts after, say, 100,000 steps and print the values seen so far. That immediately reveals whether the list is cyclic and where the cycle begins.
βοΈ Doubly-Linked Lists
Two pointers per node, both directions cheap
A doubly-linked list adds a prev pointer to every node. Now you can walk backwards as easily as forwards, and deleting a node no longer requires scanning from the head to find its predecessor β the node already knows it.
class DNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next class DoublyLinkedList: def __init__(self): self.head = None self.tail = None self._size = 0 def append(self, value): new = DNode(value, prev=self.tail) if self.tail: self.tail.next = new else: self.head = new self.tail = new self._size += 1 def prepend(self, value): new = DNode(value, next=self.head) if self.head: self.head.prev = new else: self.tail = new self.head = new self._size += 1 def forward(self): node = self.head while node: yield node.value node = node.next def backward(self): node = self.tail while node: yield node.value node = node.prev dll = DoublyLinkedList() dll.append(1) dll.append(2) dll.prepend(0) print(list(dll.forward())) # [0, 1, 2] print(list(dll.backward())) # [2, 1, 0]
| Operation | Singly | Doubly |
|---|---|---|
| Insert at head | O(1) | O(1) |
| Insert at tail (with tail pointer) | O(1) | O(1) |
| Delete a given node | O(n) | O(1) |
| Traverse forward | O(n) | O(n) |
| Traverse backward | O(n) | O(n) |
| Memory per node | 1 pointer | 2 pointers |
node.prev.next = node.next and node.next.prev = node.prev. A singly-linked list has to walk from the head to find the predecessor first. That's why LRU caches β which delete entries constantly β use doubly-linked lists.
new.prev or to update the old head's prev reference leaves the list in a state where forward traversal works but backward traversal breaks. Test both directions.π Reversing a Singly-Linked List
The classic interview problem, explained properly
Reversing a linked list is three pointer assignments in a loop. The trick is to remember the next node before you change the current node's pointer β otherwise you lose the rest of the list.
class Node: def __init__(self, value, next=None): self.value = value self.next = next def reverse(head): prev = None current = head while current: nxt = current.next # 1. remember the rest of the list current.next = prev # 2. flip this node's pointer backward prev = current # 3. advance prev current = nxt # 4. advance current return prev # prev is the new head head = Node(1, Node(2, Node(3, Node(4)))) def to_list(head): out = [] while head: out.append(head.value) head = head.next return out print("before:", to_list(head)) # [1, 2, 3, 4] head = reverse(head) print("after: ", to_list(head)) # [4, 3, 2, 1]
Step by step
Start: prev=None current=1 -> 2 -> 3 -> 4 -> None
Step 1: nxt=2
current.next = prev (1 -> None)
prev = 1
current = 2
State: prev=1 -> None current=2 -> 3 -> 4 -> None
Step 2: nxt=3
current.next = prev (2 -> 1 -> None)
prev = 2
current = 3
State: prev=2 -> 1 -> None current=3 -> 4 -> None
...and so on until current is None, at which point prev is the new head.
prev, current, and nxt. The loop body always does the same thing: save nxt, flip current.next, advance prev, advance current. Once you see that rhythm, the problem becomes mechanical.
Recursive version
def reverse_recursive(head): if head is None or head.next is None: return head new_head = reverse_recursive(head.next) head.next.next = head head.next = None return new_head # Elegant, but uses O(n) stack space. # For very long lists, the iterative version is safer.
The recursive version reads more clearly but uses O(n) stack frames. The iterative version is O(1) space. Both are O(n) time.
βοΈ Linked List vs Python List
When each one wins
| Operation | list | Linked List |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert at front | O(n) | O(1) |
| Insert at end | O(1) amortized | O(1) with tail pointer |
| Delete at front | O(n) | O(1) |
| Delete a given node | O(n) | O(n) singly, O(1) doubly |
| Search by value | O(n) | O(n) |
| Memory overhead | Low | High (one or two pointers per node) |
When linked lists are the right choice
- You insert and delete at the head constantly
- You're building another structure β a stack, a queue, a hash table, an LRU cache
- Nodes arrive out of order and need to be linked as they come
- The collection might grow or shrink dramatically at the front
When to use a Python list instead
- You need random access by index
- You're iterating more than modifying
- You're processing numerical data β contiguous memory is much friendlier to the CPU cache
- You don't have a reason to build a custom structure
list or deque almost always beats a hand-rolled linked list β the C implementation is far faster, and the memory overhead of Python objects makes the pointer nodes unusually expensive. Use linked lists to learn, and when the problem genuinely needs them.ποΈ Mini Project β An LRU Cache
Put nodes and pointers to work
An LRU (least-recently-used) cache evicts the entry that hasn't been touched for the longest. The classic implementation combines a dictionary with a doubly-linked list: the dict gives O(1) lookup, and the list gives O(1) reordering.
class Node: def __init__(self, key=None, value=None): self.key = key self.value = value self.prev = None self.next = None class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = {} # Sentinel nodes make edge cases disappear self.head = Node() self.tail = Node() self.head.next = self.tail self.tail.prev = self.head def _unlink(self, node): node.prev.next = node.next node.next.prev = node.prev def _push_front(self, node): node.next = self.head.next node.prev = self.head self.head.next.prev = node self.head.next = node def get(self, key): if key not in self.cache: return None node = self.cache[key] self._unlink(node) self._push_front(node) return node.value def put(self, key, value): if key in self.cache: self._unlink(self.cache[key]) node = Node(key, value) self.cache[key] = node self._push_front(node) if len(self.cache) > self.capacity: lru = self.tail.prev self._unlink(lru) del self.cache[lru.key] def keys(self): result = [] node = self.head.next while node is not self.tail: result.append(node.key) node = node.next return result cache = LRUCache(3) cache.put("a", 1) cache.put("b", 2) cache.put("c", 3) print(cache.keys()) # ['c', 'b', 'a'] cache.get("a") print(cache.keys()) # ['a', 'c', 'b'] cache.put("d", 4) # evicts 'b' (least recently used) print(cache.keys()) # ['d', 'a', 'c']
The design decision worth noticing is the use of two sentinel nodes β head and tail β that hold no data. They eliminate every "is this the first or last node?" special case, so _unlink and _push_front never need to check for None. This is the standard trick in production linked-list code.
β Frequently Asked Questions
Common questions about linked lists in Python
No. collections.deque is implemented as a doubly-linked list of blocks internally, but it doesn't expose node-level operations. If you need true linked-list behaviour β inserting after a specific node, for example β you build it yourself.
Most of the time, you wouldn't. Python's list is a highly optimized C array, and a hand-rolled linked list in pure Python will be slower for almost every workload. Linked lists are useful for learning the mechanics of pointers and for building other structures β LRU caches, hash tables with chaining β where the node-level operations matter. In practice, deque covers the common cases.
An array (Python's list) stores elements in one contiguous block of memory. Access by index is O(1) because the address is computed directly. A linked list scatters nodes throughout memory and connects them with pointers. Access by index is O(n) because you have to follow the chain, but insertion and deletion at a known node are O(1).
Use Floyd's tortoise-and-hare algorithm: two pointers, one moving one node per step and one moving two. If they ever meet, there's a cycle. If the fast pointer reaches None, there isn't. It's O(n) time and O(1) space, and it's a classic interview question.
Use the same two-pointer technique: advance a slow pointer one node and a fast pointer two nodes per iteration. When the fast pointer reaches the end, the slow pointer is at the middle. O(n) time, O(1) space.
Often yes. A dummy (sentinel) head node holds no data but eliminates the special case of inserting or deleting at the front. The LRU cache example above uses two sentinels β one at each end β which makes every insertion and deletion uniform. The cost is one wasted node; the benefit is that every operation looks the same.
An LRU (Least Recently Used) cache evicts the entry that hasn't been accessed for the longest time. It needs O(1) lookup (a dict) and O(1) reordering and eviction (a doubly-linked list). Neither structure alone can do both, which is why they're combined. Python's functools.lru_cache uses the same idea under the hood, implemented in C.
The bug is almost always caused by reassigning node.next before saving the old value. The fix is a one-liner: nxt = node.next before node.next = something_else. If you're debugging after the fact, walk the list from the head and count nodes β if the count is suddenly smaller than it should be, the break is at the point where the chain stops.
π Where to Go Next
Keep building on what you just learned