Sub topic 5
Deleting a node and fixing the links
This chapter assumes you can already build a singly linked list with Node and LinkedList classes and walk it with a loop. Here you will remove a node by value and handle each edge case.
The core idea
A singly linked node knows only its successor. To remove a node, you change the next reference of the node before it so that it points past the target. Nothing else in the list changes.
Because nodes link only forward, you cannot find the predecessor from the target. Your loop must stop one node early and look ahead with current.next.
The implementation
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.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 (4, 3, 2, 1):
items.push_front(v)
print(items.delete_value(3), list(items)) # True [1, 2, 4]
print(items.delete_value(1), list(items)) # True [2, 4]
print(items.delete_value(9), list(items)) # False [2, 4]The cases to handle
Each branch of delete_value covers a distinct situation.
| Situation | What happens |
|---|---|
| Empty list | There is nothing to remove, so return `False`. |
| Target is the head | No predecessor exists. Move `self.head` to `self.head.next`. |
| Target is in the middle | Set `current.next = current.next.next`. |
| Target is the last node | `current.next.next` is `None`, so the predecessor becomes the new last node. |
| Value not present | The loop reaches the end and returns `False`. |
The middle and last cases share one line of code. The head is the only special case, because it is the one node that no other node points to.
Cost
Finding the target takes O(n) because you walk from the head. The unlink itself is O(1): one reference assignment. If you already hold a reference to the predecessor, deletion is O(1) overall. This is the main advantage over an array, where removing from the middle shifts every later element.
Common errors
- Stopping on the target instead of before it. If your loop checks
current.value == value, you have passed the node you needed to modify. Checkcurrent.next.valueinstead. - Forgetting the head case. Without it, deleting the first value either fails or raises an
AttributeErroronNone. - Dereferencing
None. Writingcurrent.next.nextis safe only after you have confirmedcurrent.nextis notNone. - Deleting only the first match. The function above returns after one removal. To delete every match, keep looping and do not advance
currentafter an unlink. Otherwise you skip the node that has just moved up.
Exercise
Starting from the list 5 -> 6 -> 6 -> 7, delete_value(6) is called once. What is the list afterward, and which node's next reference changed?
Show answer
The list is 5 -> 6 -> 7. The loop stops at node 5, because its next holds the first 6. Node 5's next is set to current.next.next, which is the second 6. The first 6 is unlinked, and the second 6 stays because the function returns after one removal.