Linked Lists, Part 1: Singly Linked Lists
list and collections.deque so you can tell when it is worth using. It is part of the optional depth at the end of the track. Linked Lists, Part 2 follows with doubly linked lists and the LRU cache.After this lesson, you will be able to:
- Build a singly linked list from Node objects and explain what each next reference points at
- Implement prepend, append, find, insert after and delete, and state the cost of each
- Reverse a list in place (without copying) and find its middle node with two pointers
- Detect a cycle with a slow pointer and a fast pointer
- Choose between a linked list, a Python list and a deque using a measurement
Before you start
#Why a playlist is awkward to edit
list keeps its references side by side in one block of memory. Reading item 5000 is quick because Python can compute where it is. The price is paid on insertion: to put a song at position 0, every existing reference slides one slot to the right.| Operation | Python list | Linked list |
|---|---|---|
Read item at index i | O(1) | O(n), you walk i steps |
| Insert at the front | O(n), everything shifts | O(1) |
| Insert after a node you already hold | O(n) | O(1) |
| Find a value | O(n) | O(n) |
Insert at index i | O(n) | O(n), the walk to i dominates |
A chain holds four nodes: 1, 2, 3, 4. You want a new node at index 2, between 2 and 3. How does the cost grow with the length of the chain?
#A node holds a value and a reference
data holds the value. next holds a reference to another node, or None when nothing comes after it. Nothing about next is special. It is an ordinary attribute, and assigning it creates a link the same way any assignment makes a name refer to an object.class Node:
"""One link in the chain: a value and a reference to the next node."""
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return f"Node({self.data!r})"
a = Node("Intro")
b = Node("Verse")
c = Node("Outro")
a.next = b
b.next = c
current = a # a plain variable we move along the chain
while current is not None:
print(current.data)
current = current.nextOutput:
Intro
Verse
Outro
current starts at the first node and moves to current.next until it falls off the end as None.Step through the build below. The reference count of a node goes up each time something new refers to it, which is the memory model from earlier: a link is just one more reference.
#Prepend, and the order of two assignments
Adding to the front takes two steps: point the new node at the old head, then make the new node the head. Beginners often write them the other way round. Try it on the playlist from above and walk the first five nodes.
head = a # Intro -> Verse -> Outro
new = Node("Cold open")
head = new # step 2 done first ...
new.next = head # ... step 1 now points the node at itself
current = head
for _ in range(5): # only five steps, the chain never ends
print(current.data)
current = current.nextOutput:
Cold open
Cold open
Cold open
Cold open
Cold open
head was reassigned, new.next = head made the new node refer to itself, and nothing in the chain leads back to the old first node. A loop that waits for None would run forever. The fix is to take the old head into the new node before moving the head.head = a
new = Node("Cold open")
new.next = head # 1. the new node takes over the old chain
head = new # 2. only then does the list start at the new node
current = head
while current is not None:
print(current.data)
current = current.nextOutput:
Cold open
Intro
Verse
Outro
The same rule applies to every splice in this lesson. A splice is joining a node into the middle of a chain. Connect the new node to the part of the chain it will lead into first, and redirect the existing node last.
#The full list: append, find, insert after, delete
LinkedList class. It remembers three things: the head, the tail and the size. The tail is the last node, kept so that adding at the back needs no walk.class LinkedList:
"""Singly linked list that remembers its head, its tail and its size."""
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def prepend(self, data):
"""Add at the front. Constant time."""
node = Node(data)
node.next = self.head # 1. the new node points at the old head
self.head = node # 2. the list now starts at the new node
if self.tail is None: # the list was empty: it is also the last node
self.tail = node
self.size += 1
def append(self, data):
"""Add at the back. Constant time, because we keep the tail."""
node = Node(data)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def find(self, data):
"""Return the first node holding data, or None. Linear time."""
current = self.head
while current is not None:
if current.data == data:
return current
current = current.next
return None
def insert_after(self, node, data):
"""Insert a new node right after a node you already hold. Constant time."""
new = Node(data)
new.next = node.next # 1. the new node takes over the old successor
node.next = new # 2. only now is it safe to redirect node
if node is self.tail:
self.tail = new
self.size += 1
def delete(self, data):
"""Remove the first node holding data. Returns True if one was removed."""
if self.head is None:
return False
if self.head.data == data: # the head has no predecessor
self.head = self.head.next
if self.head is None:
self.tail = None
self.size -= 1
return True
current = self.head
while current.next is not None: # stop one node BEFORE the target
if current.next.data == data:
if current.next is self.tail:
self.tail = current
current.next = current.next.next
self.size -= 1
return True
current = current.next
return False
def reverse(self):
"""Reverse in place by flipping each next reference. Linear time."""
prev = None
curr = self.head
self.tail = self.head # the old head becomes the tail
while curr is not None:
next_node = curr.next # save it before we overwrite it
curr.next = prev # flip the arrow
prev = curr # step both pointers forward
curr = next_node
self.head = prev
def __len__(self):
return self.size
def __iter__(self):
current = self.head
while current is not None:
yield current.data
current = current.next
def __str__(self):
return " -> ".join([str(x) for x in self] + ["None"])Run the cells in order: later cells reuse the names defined above them. This one exercises the class on the playlist.
playlist = LinkedList()
for track in ["Intro", "Verse", "Outro"]:
playlist.append(track)
print(playlist, len(playlist))
playlist.prepend("Cold open")
print(playlist)
verse = playlist.find("Verse")
print(verse)
playlist.insert_after(verse, "Bridge")
print(playlist)
print(playlist.delete("Intro"), playlist.delete("Missing"))
print(playlist)Output:
Intro -> Verse -> Outro -> None 3
Cold open -> Intro -> Verse -> Outro -> None
Node('Verse')
Cold open -> Intro -> Verse -> Bridge -> Outro -> None
True False
Cold open -> Verse -> Bridge -> Outro -> None
insert_after did not need: a walk. It received the node itself, so it only rewired two references. find is where the walk lives. Calling playlist.find("Verse") and then insert_after costs O(n) in total, because the search is O(n) and the splice is O(1).| Method | Cost | Why |
|---|---|---|
prepend | O(1) | touches only the head |
append | O(1) | the tail is stored, so no walk |
find | O(n) | follows nodes until it matches |
insert_after(node, x) | O(1) | you already hold the node |
delete(x) | O(n) | the search is O(n), the unlink is O(1) |
Insert and delete nodes and watch each next reference change. Step through the pointer updates and compare them with the methods above.
In delete, the loop condition is while current.next is not None and it compares current.next.data, never current.data. Why does it look one node ahead?
#Reversing a list
previs the part already reversed.curris the node being flipped.next_nodeis the rest of the chain. Save it first, because flippingcurr.nextwould otherwise cut it off.
1 -> 2 -> 3 by hand. At the start prev is None and curr is node 1.| Pass | next_node saved | Arrow flipped | prev after | curr after |
|---|---|---|---|---|
| 1 | node 2 | 1 now points at None | node 1 | node 2 |
| 2 | node 3 | 2 now points at 1 | node 2 | node 3 |
| 3 | None | 3 now points at 2 | node 3 | None |
curr is None, and prev is the new head. Now the same steps in code.def reverse(head):
"""Reverse a chain of nodes and return the new head."""
prev = None
curr = head
while curr is not None:
next_node = curr.next # 1. remember where the rest of the chain is
curr.next = prev # 2. flip the arrow backwards
prev = curr # 3. the reversed part now begins at curr
curr = next_node # 4. move on to the rest
return prev
def show(head):
parts = []
while head is not None:
parts.append(str(head.data))
head = head.next
return " -> ".join(parts + ["None"])
x, y, z = Node(1), Node(2), Node(3)
x.next = y
y.next = z
print(show(x))
head = reverse(x)
print(show(head))Output:
1 -> 2 -> 3 -> None
3 -> 2 -> 1 -> None
prev is the last node that was processed, which is the new head. The class method does the same and sets self.tail = self.head first. The old first node becomes the last one, and it is easy to lose track of it once the loop has run.FixThisCode below uses a version of this function with one line in the wrong place.This reverse runs without an error, but a three-node list comes back with a single node. One line reads curr.next after it has already been overwritten. Fix it so the output is 3 -> 2 -> 1 -> None.
3 -> 2 -> 1 -> None
#Finding the middle with two pointers
slow moves one node per step and fast moves two. When fast runs off the end, slow has covered half the distance.def find_middle(head):
"""Return the middle node. For an even length, the second of the two middles."""
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slow
for length in (1, 2, 3, 4, 5, 6):
chain = LinkedList()
for i in range(1, length + 1):
chain.append(i)
print(length, find_middle(chain.head))
print(find_middle(None))Output:
1 Node(1)
2 Node(2)
3 Node(2)
4 Node(3)
5 Node(3)
6 Node(4)
None
fast is not None stops an even-length list, where fast lands on None. fast.next is not None stops an odd-length list, where fast lands on the last node and fast.next.next would fail. Swap the two checks and an empty list raises AttributeError.#Detecting a cycle
next leads back to an earlier node, the chain never ends, and a loop that waits for None runs forever. In the list this lesson builds, a cycle is a bug. Some designs use a circular list on purpose, with a rule for where to stop. Accidental cycles are easy to create when you splice carelessly, as the self-referencing node above showed.slow one step and fast two steps. With no cycle, fast reaches None and you are done. With a cycle, both end up circling inside it. Each step, fast gains one node on slow, so it must eventually land on the same node. This is Floyd's cycle-finding algorithm, also called tortoise and hare.def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast: # the very same node object, not merely an equal one
return True
return False
chain = LinkedList()
for i in range(1, 6):
chain.append(i)
print(has_cycle(chain.head))
chain.tail.next = chain.find(3) # the last node now leads back to 3
print(has_cycle(chain.head))
current = chain.head
walk = []
for _ in range(8): # a plain walk would never stop
walk.append(current.data)
current = current.next
print(walk)Output:
False
True
[1, 2, 3, 4, 5, 3, 4, 5]
set. It also works and is easier to read, but it uses O(n) space. Finding the node where the cycle begins takes a second phase of the same idea, which is outside this lesson.#When a linked list is the wrong choice in Python
Everything above is correct, and in Python it is still rarely what you want. Three reasons come from how Python works.
- Every node is a full Python object with its own attribute storage.
- Walking the chain means following a reference per node instead of reading consecutive memory.
- The CPython
listanddequeare written in C, so their loops cost far less per step than a loop you write in Python.
The playlist's front-insertion claim is the thing to measure. Three ways to add n items at the front, from an empty start:
import time
from collections import deque
def best_time(fn, repeats=2):
best = float("inf")
for _ in range(repeats):
start = time.perf_counter()
fn()
best = min(best, time.perf_counter() - start)
return best
def front_list(n):
items = []
for i in range(n):
items.insert(0, i)
def front_deque(n):
items = deque()
for i in range(n):
items.appendleft(i)
def front_linked(n):
items = LinkedList()
for i in range(n):
items.prepend(i)
for n in (1_000, 10_000, 30_000):
print(n, f"list {best_time(lambda: front_list(n)):.4f}s",
f"deque {best_time(lambda: front_deque(n)):.4f}s",
f"linked {best_time(lambda: front_linked(n)):.4f}s")The numbers depend on your machine. In one run on a laptop with Python 3.12, 1,000 insertions took well under a millisecond for all three, and 30,000 insertions took about 0.05 s for the list, 0.005 s for the linked list and 0.0004 s for the deque. The ratios matter more: the list was about 10 times slower than the linked list and over 100 times slower than the deque. Three things to read from that. At small sizes the difference does not matter. The list's cost grows much faster than the others as n grows. And the deque beats the hand-written linked list at the one thing a linked list is supposed to be good at.
Now the other direction: reading from the middle, and the memory used.
import tracemalloc
n = 100_000
as_list = list(range(n))
as_deque = deque(as_list)
as_linked = LinkedList()
for x in as_list:
as_linked.append(x)
def nth(linked, i):
current = linked.head
for _ in range(i):
current = current.next
return current.data
print("100 lookups of index 50000 in", n, "items")
print(f"list {best_time(lambda: [as_list[50_000] for _ in range(100)]):.6f}s")
print(f"deque {best_time(lambda: [as_deque[50_000] for _ in range(100)]):.6f}s")
print(f"linked {best_time(lambda: [nth(as_linked, 50_000) for _ in range(100)]):.6f}s")
def megabytes(build): # machine dependent: compare ratios, not absolute sizes
tracemalloc.start()
keep = build()
current, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current / 1e6
def build_linked():
items = LinkedList()
for i in range(100_000):
items.append(i)
return items
list_bytes = megabytes(lambda: list(range(100_000)))
linked_bytes = megabytes(build_linked)
print(f"the linked list holds the same items in about {linked_bytes / list_bytes:.0f} times the memory")In an earlier run on a similar laptop, 100 lookups of index 50,000 took about 2 microseconds for the list, 0.4 milliseconds for the deque and 60 milliseconds for the linked list. The linked list used about three times the memory of the list for the same 100,000 integers, because each node adds an object and its attributes to the integer it carries. The absolute sizes depend on the machine and on whether Python is 32-bit (as in the browser) or 64-bit, so the cell prints only the ratio. These are example measurements, not guarantees.
deque is itself a doubly linked list, but of fixed-size blocks of items instead of single items, so it gets O(1) work at both ends without the cost of an object per element. That is why it wins at the front. It does give up fast indexing in the middle, as the second row shows.Which structure does each of three small jobs want?
| Job | Operations | Best fit in Python |
|---|---|---|
| Browser history, with a back button | add a page at the end, remove the latest page | list with append and pop |
| Undo stack | push an action, pop the latest | list with append and pop |
| Play queue, next song comes from the front | add at the back, remove from the front | collections.deque with append and popleft |
Both stacks work at one end of a Python list, where it is already O(1), so a hand-written linked list only adds code and memory. The queue needs fast work at both ends, which is exactly what a deque gives.
A hand-written linked list does earn its place in a few cases:
- You hold direct references to nodes and splice at them repeatedly, as in the LRU cache in Part 2.
- You are building trees or graphs. These are nodes with several
nextreferences, and they use the same skills. - The point of the exercise is to practise rewiring references.
list and move to deque if you take from the front.#Common mistakes
Three bugs account for most broken linked lists. Each example below fails quietly or with a short error, so you can run it.
Moving the head while walking
self.head itself to walk the list, nothing is left referring to the chain.songs = LinkedList()
for s in ["a", "b", "c"]:
songs.append(s)
while songs.head: # BUG: walks with the only handle on the list
songs.head = songs.head.next
print(songs.head, len(songs), list(songs))Output:
None 3 []
current = songs.head and then current = current.next leaves songs.head where it was.Reading .next on an empty list
while current.next is not None is the right test for delete, and the wrong one for traversal, because an empty list has no first node to ask.empty = LinkedList()
try:
current = empty.head
while current.next is not None:
current = current.next
except AttributeError as error:
print(type(error).__name__, error)Output:
AttributeError 'NoneType' object has no attribute 'next'
while current is not None, which handles it for free.Forgetting the tail
tail has one more thing to keep right. If you unlink the last node by hand and leave tail alone, the next append attaches to a node that is no longer in the list.songs = LinkedList()
for s in [1, 2, 3]:
songs.append(s)
songs.head.next.next = None # BUG: removed the last node, tail still points at it
songs.size -= 1
songs.append(99)
print(songs, len(songs))Output:
1 -> 2 -> None 3
delete, which moves the tail back to the previous node, or to update songs.tail yourself.#Try it
pop_front method that returns the removed value, raises IndexError on an empty list and keeps tail and size correct. The starter has the rest of the class.Tests: assert len(undo) == 0; assert undo.tail is None and undo.head is None; undo.prepend('x'); assert undo.pop_front() == 'x'
head. The empty list is checked first. The one-node case is the one that needs tail = None.history = [] and history.append(...) and history.pop(). The list version is shorter and faster, and writing the linked one once shows you what the list was doing for you.#Recap
head reference is the way in. Prepending and inserting after a node you hold are O(1), because they rewire two references. Finding a value, or reaching an index, is O(n), because you can only follow the chain. Deleting needs the node before the target, because that node owns the reference that has to change.Three patterns cover the rest. Reversal saves the next node, flips the arrow, and steps forward. A slow and a fast pointer find the middle in one pass. The same pair detects a cycle when they land on the same node. In every splice, connect the new node first and redirect the existing node last.
list is better for indexing and for stacks. A deque is better for queues. The measurements above show by how much. The value of this lesson is the skill of rewiring references, which you will use again for trees and in Linked Lists, Part 2.#Quiz
A chain holds 1, 2, 3, 4, 5, 6 and you call find_middle(head) from this lesson. Which node does it return?