10/39
Part 2 of 7 · Pointer orderLearn and do
Overwrite a pointer only once something else holds what it pointed at
Node(val, node.next) reads the old node.next before the assignment overwrites it. Write the insert in two steps the other way round and the rest of the list is gone:
def insert_after_wrong(node, val):
new = Node(val)
node.next = new
# node.next is new by now, so new points at itself
new.next = node.next
head = linked([3, 1, 4])
insert_after_wrong(head, 9)
values(head, limit=10)
ValueError: more than 10 nodes: a cycle, or a very long list
The 9 points at itself, and nothing points at the 1 anymore:
the walk
3
→9
→back to 9 itselfThe walk: 3, 9, 9, 9, ...
lost
1
→4
Nothing points at 1 anymore.
Without the limit, that walk appends 9 forever. So here is the rule for every pointer change: before you overwrite a pointer, make sure something else still holds what it pointed at.
In the editor, write swap_first_two(head): move the nodes, not the values, in an order that never loses the rest. It prints the swapped list, and whether the old head is now second.