Sub topic 4
Inserting at the front, the back, and after a node
This chapter assumes you can write a Python class with fields and methods, and that you know the Node and LinkedList classes from the earlier chapters. It also assumes you can read introductory Big-O notation. Insertion is where linked lists show their strengths. Every insertion comes down to the same operation: building a node and rewiring one or two next references.
The rule behind every insertion
To insert a new node, do two things in this order:
- Point the new node's
nextat the node that will follow it. - Point the previous node's
next(or the list'shead) at the new node.
The order matters. In step 1 you copy a reference you still have. If you reverse the steps, you overwrite the only reference to the rest of the list. Those nodes become unreachable and Python's garbage collector frees them.
The three insertion positions differ only in where the "previous" reference lives and how far you walk to reach it.
| Position | Previous reference | Work to find it | Total cost |
|---|---|---|---|
| Front | `self.head` | none | O(1) |
| Back | last node's `next` | walk the whole list | O(n) |
| After a given node | that node's `next` | none, you already hold it | O(1) |
| At index i | node at index i-1 | walk i-1 steps | O(i) |
Inserting at the front
Inserting at the front needs no walk, because the list already holds a reference to its first node. The new node takes the old head as its next, and then the list's head moves to the new node.
The code in the spine does both steps in one line. The expression Node(value, self.head) runs first, so it reads the old head before the assignment replaces it.
self.head = Node(value, self.head)This works unchanged on an empty list. The old head is None, so the new node becomes a one-node list whose next is None. Front insertion has no special case for empty lists.
Inserting at the back
The list stores only the head, so reaching the end means walking every node. The loop condition is current.next is not None, not current is not None. The loop must stop on the last node, because you need that node in order to change its next. If the loop ran until current was None, you would have walked past the end and lost the reference you needed.
An empty list is a special case. There is no last node, so the new node becomes the head.
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_nodeThis is O(n) for every call. Building a list of n items with repeated append calls therefore costs 0 + 1 + 2 + ... + (n-1) steps, which is O(n²) in total. Building the same list with push_front is O(n), but the items end up in reverse order. If you need to build in order, you can push the items in reverse, or keep a tail pointer, shown below.
Keeping a tail pointer
A list can store a second reference, tail, that always points to the last node. Then append needs no walk. The cost is that every operation that can change the last node must keep tail correct. Two cases are easy to forget:
- Pushing onto an empty list must set
tailas well ashead. - Deleting the last node must move
tailbackwards. A singly linked list cannot do that in O(1), because it cannot step backwards from the tail. This is one reason the doubly linked list exists.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class TailLinkedList:
def __init__(self):
self.head = None
self.tail = None
def push_front(self, value):
self.head = Node(value, self.head)
if self.tail is None:
self.tail = self.head
def append(self, value):
new_node = Node(value)
if self.tail is None:
self.head = self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
items = TailLinkedList()
items.append(1)
items.append(2)
items.push_front(0)
items.append(3)
print(list(items)) # [0, 1, 2, 3]The check self.tail is None and the check self.head is None are equivalent here, because the two fields are empty together or set together. If your code lets them disagree, a bug is already present.
Inserting after a given node
When you already hold a reference to a node, inserting after it is O(1). No walk is needed, because node.next is already the "previous reference" from the rule above.
def insert_after(self, node, value):
node.next = Node(value, node.next)The right side runs first and reads the old node.next. The assignment then replaces it. This one line is the whole algorithm, and it works when node is the last node as well. In that case the new node's next is None, so the new node becomes the last node. With a tail pointer you would also need if node is self.tail: self.tail = node.next after the assignment.
This operation has two limits you should know about:
- It cannot insert before a node. A singly linked node does not know its predecessor, so inserting before it needs a walk from the head to find that predecessor.
- The reference you hold must belong to this list. Nothing checks it. If you pass a node from another list, you silently splice the lists together.
Because the operation is cheap, it is the right tool when a search or traversal has already found the position. For example, you can walk a sorted list to find where a value belongs and insert there in the same pass, using one insert_after call.
Inserting at an index
Index-based insertion combines the cases above. Index 0 is a front insertion. Any other index requires you to find the node at index - 1 and insert after it.
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 insert_at(self, index, value):
if index < 0:
raise IndexError("index must not be negative")
if index == 0:
self.push_front(value)
return
current = self.head
for _ in range(index - 1):
if current is None:
break
current = current.next
if current is None:
raise IndexError("index out of range")
current.next = Node(value, current.next)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
items = LinkedList()
for v in (30, 10):
items.push_front(v)
items.insert_at(1, 20) # between 10 and 30
items.insert_at(3, 40) # at the end, index equals length
print(list(items)) # [10, 20, 30, 40]
try:
items.insert_at(9, 99)
except IndexError as error:
print(error) # index out of rangeThe valid indexes are 0 through the list's length, inclusive. An index equal to the length means "at the back". The break inside the loop stops the walk early when the list is too short, and the None check after the loop turns that into an error. Without that check, a too-large index would fail with AttributeError on None, a confusing message for the caller.
Common errors
- Losing the tail of the list. This is the order-of-operations mistake described at the start. If your list shrinks after an insert, check the order of your two assignments first.
- Stopping the append loop one node too late. Using
while current is not NoneleavescurrentasNone, and the next line raisesAttributeError. - Forgetting the empty list.
appendon an empty list must sethead. Test every insertion on an empty list, a one-node list, and a longer list. - Stale tail pointer. If you add a tail, run each operation against it, including operations you wrote earlier.
- Using
appendin a loop for large inputs. The O(n²) total cost is invisible on ten items and very visible on a hundred thousand.
Exercise
A LinkedList has no tail pointer and holds 1,000 nodes. You call append once, then insertafter on a node you already hold, then pushfront. How many nodes does each call visit, and which of the three would you avoid inside a loop over many items?
Show answer
append visits all 1,000 nodes to reach the last one, so it is O(n). insertafter visits none, so it is O(1). pushfront visits none, so it is O(1). You would avoid append inside a loop, because n calls cost O(n²) in total. Use push_front and accept reversed order, or add a tail pointer.
Exercise
Write insertaftervalue(self, target, value) for the LinkedList class. It should insert value after the first node whose value equals target and return True. If no node matches, it should return False and leave the list unchanged. What is its time complexity?
Show answer
def insertaftervalue(self, target, value): current = self.head while current is not None: if current.value == target: current.next = Node(value, current.next) return True current = current.next return False The search walks up to n nodes, so the method is O(n). The insertion itself is O(1), so the search dominates the cost.