Sub topic 4
Inserting at the ends and after a given node
This chapter assumes you know how a singly linked list stores a next reference, can read Python classes and generators, and can use Big-O notation. It builds on the doubly linked node from the previous chapters, where each node holds prev and next, and the list holds head, tail and size.
Why insertion needs care
Insertion in a doubly linked list rewires up to four references. The new node needs a prev and a next. Its neighbors need to point back at it. If you update them in the wrong order, or skip a neighbor that does not exist, the list breaks quietly. Most bugs come from two places: the empty list and the ends.
Inserting at the front
push_front makes the new node point forward to the old head. If a head exists, that head must point back to the new node. If the list is empty, the new node is also the tail.
class Node:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def push_front(self, value):
node = Node(value)
node.next = self.head
if self.head is not None:
self.head.prev = node
else:
self.tail = node
self.head = node
self.size += 1
return node
def push_back(self, value):
node = Node(value)
node.prev = self.tail
if self.tail is not None:
self.tail.next = node
else:
self.head = node
self.tail = node
self.size += 1
return node
def insert_after(self, node, value):
new = Node(value)
new.prev = node
new.next = node.next
if node.next is not None:
node.next.prev = new
else:
self.tail = new
node.next = new
self.size += 1
return new
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
def reversed(self):
node = self.tail
while node is not None:
yield node.value
node = node.prev
lst = DoublyLinkedList()
first = lst.push_back(1)
last = lst.push_back(3)
lst.insert_after(first, 2)
lst.insert_after(last, 4)
lst.push_front(0)
print(list(lst)) # [0, 1, 2, 3, 4]
print(list(lst.reversed())) # [4, 3, 2, 1, 0]Inserting at the back
push_back is the mirror image. The new node's prev is the old tail, and the old tail's next is the new node. Because the list keeps a tail reference, this takes O(1) time. A singly linked list with only a head would need to walk the whole list first.
Each method returns the node it created. Returning the node lets callers keep a reference for later calls to insert_after.
Inserting after a given node
insert_after(node, value) works in O(1) time because you already hold node. You do not search for it, and the prev pointer means you never need to find a predecessor. The method follows four steps:
- Create
newand setnew.prev = node. - Set
new.next = node.next, which copies the old successor. - Fix the successor. If it exists, set its
prevtonew. Ifnodewas the tail, updateself.tail. - Set
node.next = new.
Edge cases to check
| Situation | What must change |
|---|---|
| Insert into an empty list | `head` and `tail` both become the new node |
| `push_front` on a non-empty list | Old head's `prev` is set, `head` changes, `tail` does not |
| `push_back` on a non-empty list | Old tail's `next` is set, `tail` changes, `head` does not |
| `insert_after` the tail | `tail` changes to the new node |
A one-element list is the best test. Its single node is both head and tail, so any branch that forgets one of those roles shows up at once.
Exercise
In insert_after, why does the method need an else branch that sets self.tail = new, and what would go wrong without it?
Show answer
The else branch runs when node.next is None, which means node was the tail. The new node then becomes the last node. Without the update, tail would still point to the old last node. A later push_back would attach the new node in the middle, and reversed() would start from the wrong node and skip the inserted value.