9/39
Part 2 of 7 · Pointer orderLearn and do
Change pointers in an order that never loses the rest
Most of the work on a linked list is moving one or two pointers. The skill is the order you move them in.
def insert_after(node, val):
# the new node takes over node's old next
node.next = Node(val, node.next)
def delete_after(node):
# step over the node after
node.next = node.next.next
head = linked([3, 1, 4])
insert_after(head, 9)
print(values(head))
delete_after(head)
print(values(head))
[3, 9, 1, 4]
[3, 1, 4]
insert_after makes the new node point at 1 first, and only then moves 3's pointer to it:
before
3
→1
→4
step 1: Node(9, node.next)
9
→1
→4
3 still points at 1 too.
step 2: node.next = the new node
3
→9
→1
→4
delete_after changes one pointer so it skips a node:
before
3
→1
→4
after
3
→4
left over
1
→4
1 still points at 4, but nothing points at 1. No walk from the head reaches it.
delete_after takes the node before the one to delete. In a singly linked list a node doesn't know which node points at it. So you can only unhook a node from the node before it, its predecessor. The doubly linked list further down lifts that limit.
In the editor, write insert_sorted(head, val), which returns the head because a small value becomes the new one. It inserts 5, then 0, into a sorted list.