25/39
Part 5 of 7 · Doubly linked listsLearn and do

In insert_after, set the old neighbor's prev before you change node.next

The order inside insert_after matters again. Its first line only sets the new node's own pointers. The last two lines change the neighbors, and node.next.prev = new has to come first, while node.next is still the old neighbor. Swap them:

def insert_after_swapped(node, new):
    new.prev, new.next = node, node.next
    node.next = new
    # node.next is new by now, so this sets new.prev
    node.next.prev = new


head, tail = DNode(), DNode()
head.next, tail.prev = tail, head
first = DNode("a")
insert_after_swapped(head, first)
print(first.prev is first, tail.prev is head)
for key in "bc":
    insert_after_swapped(tail.prev, DNode(key))
print(forward(), backward())
Predict

insert_after_swapped sets node.next = new before node.next.prev = new. After inserting a, b and c, what does backward() return?

Pick one to see what it prints.
Pick an answer above to see the rest