Sub topic 5
Deleting a node and fixing the links
This chapter assumes you can read the Node and LinkedList classes from the earlier chapters, with push_front, append, and a generator-based __iter__. It also assumes you know Big-O notation at an introductory level. Here you will implement deletion by value, by position, and after a known node. You will also see the bugs that deletion most often causes.
What deletion means in a linked list
A linked list has no array to shift. Nodes are separate objects joined by next references. To delete a node, you change one reference so that the chain skips it.
If the list is 1 -> 2 -> 3 and you want to delete 2, the node holding 1 must now point to the node holding 3. The node holding 2 is not edited. It becomes unreachable, and nothing in the list refers to it any more.
The key point is that you must hold the node before the target. A singly linked node only knows what comes after it, so the target cannot repair the node that points to it. You find the predecessor by walking the list, and that walk is why deletion by value costs O(n).
Two cases: the head and everything else
The head is special because nothing points to it except the list object itself. Deleting the head means changing self.head. Deleting any other node means changing the next of its predecessor.
| Case | What you change | Cost |
|---|---|---|
| Delete the head | `self.head = self.head.next` | O(1) |
| Delete a middle node | `predecessor.next = predecessor.next.next` | O(n) to find it, O(1) to unlink |
| Delete the last node | `predecessor.next = None` | O(n) to find the second-to-last node |
| Delete a missing value | Nothing | O(n) full scan |
The last row matters in practice. A search that fails still walks the whole list, so callers should be told that nothing was removed.
Deleting by value
This version looks one node ahead. The loop variable current is the predecessor, and current.next is the candidate for deletion. Looking ahead is what lets you unlink without a separate prev variable.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
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_node
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def delete_value(self, value):
if self.head is None:
return False
if self.head.value == value:
self.head = self.head.next
return True
current = self.head
while current.next is not None:
if current.next.value == value:
current.next = current.next.next
return True
current = current.next
return False
items = LinkedList()
for v in (1, 2, 2, 3, 4):
items.append(v)
print(items.delete_value(2)) # True
print(list(items)) # [1, 2, 3, 4]
print(items.delete_value(9)) # False
print(items.delete_value(1)) # True, the head was removed
print(list(items)) # [2, 3, 4]
print(items.delete_value(4)) # True, the tail was removed
print(list(items)) # [2, 3]Three details are worth checking against the output:
- The empty-list check comes first, so
self.head.valuenever runs onNone. - The head is tested separately, because the loop only ever inspects
current.nextand so never looks at the head itself. - Only the first match is removed. The second
2stays after the first call.
Deleting the tail needs no extra code. When current.next is the last node, current.next.next is None, so the assignment sets current.next = None. The list now ends at current.
Deleting every match
Removing all occurrences of a value shows the most common deletion bug. After you unlink a node, the new current.next has not been examined yet. If you advance current anyway, you skip it. Advance only when nothing was removed.
def delete_all(self, value):
removed = 0
while self.head is not None and self.head.value == value:
self.head = self.head.next
removed += 1
current = self.head
while current is not None and current.next is not None:
if current.next.value == value:
current.next = current.next.next
removed += 1
else:
current = current.next
return removedAdd this method inside LinkedList. The first loop strips matching nodes from the front, because several head nodes in a row may match. The second loop handles the rest. On [1, 2, 2, 3], deleting 2 removes both nodes. If the else were missing, the second 2 would be skipped and one match would survive.
Deleting by position and after a node
Deleting by index follows the same pattern. You walk to the predecessor, so the cost is O(index). The checks below turn a bad index into a clear IndexError instead of an AttributeError on None.
def delete_at(self, index):
if index < 0 or self.head is None:
raise IndexError("index out of range")
if index == 0:
value = self.head.value
self.head = self.head.next
return value
current = self.head
for _ in range(index - 1):
current = current.next
if current is None:
raise IndexError("index out of range")
if current.next is None:
raise IndexError("index out of range")
removed = current.next
current.next = removed.next
return removed.valueAdd this to LinkedList as well. There are two separate failure points. The loop can run off the end while looking for the predecessor. The predecessor can also exist while current.next is None, which happens when the index equals the length.
If the caller already holds a reference to the predecessor, deletion needs no search at all:
def delete_after(node):
if node.next is None:
return None
removed = node.next
node.next = removed.next
removed.next = None
return removed.valueThis is O(1). It is the reason linked lists are attractive when you keep references to nodes, for example from an earlier search. Clearing removed.next is optional in Python. It prevents a detached node from keeping the rest of the chain reachable if something else still holds that node.
Memory after deletion
In Python, an unlinked node is reclaimed by the garbage collector once no references remain. In C or C++ you must free it yourself, and you must read next before freeing. A typical C sequence saves the pointer to the following node, frees the target, then relinks. Reading a freed node is undefined behavior.
Edge cases to test
Test every deletion function against the same small set of situations:
- An empty list.
- A one-element list, deleting the only value, which must leave
headasNone. - Deleting the head of a longer list.
- Deleting the tail.
- A value that is not present.
- Duplicates next to each other.
The one-element case catches code that updates current.next but forgets that the head itself changed. The adjacent-duplicates case catches the skipped-node bug described earlier.
Looking ahead
The special handling of the head is the main source of clutter in these functions. The sentinel chapter shows how a dummy node before the head removes that branch. The doubly linked chapter shows how a prev reference lets you delete a node in O(1) when you hold only the node itself.
Exercise
A list holds [5, 5, 5, 7]. You call delete_all(5) using a loop that always executes current = current.next after the comparison, whether or not a node was removed. The head-stripping loop is already in place. What does the list contain afterwards, and why?
Show answer
With the head-stripping loop in place, all three leading 5s are removed before the second loop starts, so the result is [7] and the bug does not show. The bug appears when the matches are not at the head, for example [1, 5, 5, 7]. Removing the first 5 leaves the second 5 in current.next, and advancing current moves past it, so the result is [1, 5, 7]. The fix is to advance only in the else branch.
Exercise
Write delete_last(self) for the LinkedList class. It should remove the last node, return its value, and raise IndexError on an empty list. What is its time complexity, and why can it not be O(1) in a singly linked list?
Show answer
def delete_last(self): if self.head is None: raise IndexError("delete from empty list") if self.head.next is None: value = self.head.value self.head = None return value current = self.head while current.next.next is not None: current = current.next value = current.next.value current.next = None return value It is O(n). The node before the last one is the only one that can be changed, and a singly linked list has no way to reach it except by walking from the head.