Sub topic 2
Deleting a Node and Fixing the Links
Assume you know Python references, loops, functions, classes, and introductory Big-O notation. A linked list stores values in nodes. Each node points to the next node.
Deleting a Node
To delete a value from a singly linked list, find the node before it. Change that node’s next reference to skip the target. If the target is the head, move head to the second node.
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def delete_value(head, value):
if head is None:
return None
if head.value == value:
return head.next
current = head
while current.next is not None:
if current.next.value == value:
current.next = current.next.next
break
current = current.next
return headThe search takes O(n) time. Once the target and its predecessor are known, changing the link takes O(1) time. The operation uses O(1) extra memory.
Linked Lists Versus Arrays
An array stores elements in adjacent positions and supports fast indexing. A linked list must walk from its head to reach an index.
| Operation | Array | Singly linked list |
|---|---|---|
| Access by index | O(1) | O(n) |
| Search | O(n) | O(n) |
| Insert or delete at front | O(n) | O(1) |
| Insert or delete after a known node | O(n) | O(1) |
Arrays usually use memory more efficiently because linked-list nodes also store references. Linked lists are useful when frequent link changes matter more than indexing.
Sentinel Nodes and Simpler Edge Cases
A sentinel, or dummy node, is an extra node before the real head. It lets deletion use the same rule for the first node and every other node. After the operation, return dummy.next.
Reversing a List in Place
To reverse a list, save the next node before changing the current node’s link. Then point the current node backward and advance both references.
def reverse(head):
previous = None
current = head
while current is not None:
following = current.next
current.next = previous
previous = current
current = following
return previousThis runs in O(n) time and uses O(1) extra memory.
Exercise
Why must following be saved before assigning current.next = previous?
Show answer
The original current.next is the only reference to the remaining part of the list. Saving it prevents that part from being lost.