Sub topic 4
Inserting at the front, the back, and after a node
This chapter assumes you can read the Node and LinkedList classes from earlier chapters, know that head is a reference to the first node (or None), and understand O(1) versus O(n). Insertion in a singly linked list always comes down to one thing: choosing the order in which you change references so that no node is lost.
Setup
Here is the starting code again. push_front is already included.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
self.head = Node(value, self.head)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.nextInserting at the front
push_front does two things in one line. It creates a new node whose next is the current head, then moves head to the new node. The old chain stays intact behind the new node.
This takes O(1) time. No traversal is needed, because the list always knows where its first node is. It also works on an empty list: self.head is None, so the new node's next is None.
Inserting at the back
The list stores only head, so reaching the last node means walking the whole chain. That makes append O(n).
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next is not None:
current = current.next
current.next = new_nodeThe loop stops at the last node, not past it. If it stopped at None, you would have no node left to attach to.
The empty list is a separate case. With no head, there is no current.next to read, so the code sets head directly.
Inserting after a node
Sometimes you already hold a reference to a node and want to insert right after it. That is O(1), because there is no search.
def insert_after(self, node, value):
node.next = Node(value, node.next)The order matters. The new node captures node.next first, as its own next. Only then does node.next change to point at the new node. In the code above, Python evaluates Node(value, node.next) before the assignment, so the order is correct.
The wrong order loses data:
# Wrong: the rest of the list becomes unreachable
new_node = Node(value)
node.next = new_node
new_node.next = node.next # now points at new_node itselfAfter node.next = new_node, the old successor is no longer referenced by anything you can reach, and the last line makes the new node point at itself.
Costs at a glance
| Operation | Time | Why |
|---|---|---|
| Insert at front | O(1) | Only `head` changes |
| Insert at back | O(n) | Must walk to the last node |
| Insert after a known node | O(1) | Only two references change |
| Insert at index k | O(k) | Walk to position k, then O(1) |
Common errors
- Forgetting the empty-list case in
append, which raisesAttributeError: 'NoneType' object has no attribute 'next'. - Updating
node.nextbefore saving the old value. - Walking until
current is Nonewhen appending, which leaves no node to attach to.
Try it
items = LinkedList()
items.push_front(2)
items.push_front(1)
items.append(4)
second = items.head.next
items.insert_after(second, 3)
print(list(items)) # [1, 2, 3, 4]You will also need to put append and insert_after inside the LinkedList class (indented as shown above) for this to run.
Exercise
A list holds 5 -> 8 -> 9. You run insert_after(node_8, 7) where node_8 is the node holding 8. What does the list contain afterward, and how many references changed?
Show answer
The list is 5 -> 8 -> 7 -> 9. Two references were set: the new node's next now points to the node holding 9, and node_8's next now points to the new node. No traversal was needed, so the operation is O(1).
Exercise
Why is append O(n) in this implementation, and what change would make it O(1)?
Show answer
The list stores only a head reference, so append must walk every node to find the last one. Keeping a tail reference in the list makes the last node reachable directly, so append can attach to it in O(1), as long as tail is updated whenever the last node changes.