Nodes and links: building and walking a linked list
🌍 In real life. At the school picnic there is a treasure hunt. The first clue is handed to you; it says "look under the big mango tree". Under the tree is the next clue, pointing to the well, and so on, until a clue says "the treasure is here". The clues are scattered all over the field, not in a row, and you can't jump straight to the fifth clue: the only way to reach it is to start at the first one and follow where each clue points.
That is a linked list: items scattered in memory, each one telling you where the next one is.
The idea in one sentence: a linked list is a chain of nodes, where each node keeps a value and a reference to the next node, and the whole list is known by its first node, the head.
Its words:
- node: a small object with two parts,
val(the value) andnext(the next node) - link (or reference): the
nextpart, pointing at another node - head: the first node; None: what the last node's
nextholds, meaning "the end" - walk (traverse): visit the nodes in order by following
next
How it works, step by step:
- a class
Nodewithvalandnext - build from the back:
head = Node(4), thenhead = Node(1, head), thenhead = Node(3, head)gives 3 → 1 → 4 - walk:
cur = head, thenwhile cur:usecur.val, thencur = cur.next
Watch cur hop along the chain, adding up the values:
Why it is correct. Each node's next names exactly the node after it, so following next from the head visits every node once, in order. The walk stops because the last node's next is None, and while cur: is false for None. (A list whose last link points back into itself never ends: that is a cycle, and 41.4 shows how to catch one.)
What it costs, worked out.
- walking all n nodes: n hops, O(n)
- reaching position i: i hops from the head, O(n). A Python list does
a[i]in one step, because its items sit in a row of numbered boxes (Chapter 34) - memory: every node is a whole Python object holding a value and a reference, so a linked list of numbers takes noticeably more memory than a plain list
So why bother? Because changing a linked list is cheap where a list is expensive (41.2), and the same idea, nodes with links, builds trees and graphs in the worlds ahead.
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def from_list(values):
head = None
for v in reversed(values): # build from the back
head = Node(v, head)
return head
def to_list(head):
out = []
cur = head # walk with cur; keep head where it is
while cur:
out.append(cur.val)
cur = cur.next
return out
head = from_list([3, 1, 4, 1, 5])
print(to_list(head))
print(head.val, head.next.val, head.next.next.val)Mistakes and edge cases.
- forgetting
cur = cur.next: the loop never ends while cur.next:stops one node early, so the last value is skipped (and an empty list crashes)- moving
headitself instead of acurcopy: afterwards you can't find the start of the list again - going past the end, as in
None.val, raisesAttributeError: 'NoneType' object has no attribute 'val' - an empty linked list is just
head = None
Quiz
What does this print?
class Node: def __init__(self, val, next=None): self.val = val self.next = next head = Node(5, Node(6, Node(7))) out = [] cur = head while cur: out.append(cur.val * 10) cur = cur.next print(out)How many hops does it take to reach the 1000th node of a linked list?
- 999, starting from the head: O(n)
- 1, like a[999]: O(1)
- About 10, by halving: O(log n)
This should print every value of the list 3 → 1 → 4, but it prints only 3 and 1. Which line is wrong?
class Node: def __init__(self, val, next=None): self.val = val self.next = next head = Node(3, Node(1, Node(4))) cur = head while cur.next: print(cur.val) cur = cur.nextWhat does this print?
class Node: def __init__(self, val, next=None): self.val = val self.next = next head = None for v in [8, 2, 6]: head = Node(v, head) print(head.val, head.next.val)
Coding tasks
Using the
Nodeclass, writeto_list(head): walk the linked list and give back its values as a Python list ([]for an empty list,head = None).Fix
from_list(values): build a linked list with the values in the same order and give back its head (None for an empty list).Write
nth_value(head, i): the value at position i (0 is the head). If the list has no position i, raiseIndexError.