Linked List Operations
This lesson implements the standard operations on a singly linked list: traversal, finding the lowest value, inserting at a position, deleting a value, reversing the list, and detecting a cycle. All of them are variations of the same loop: start at the head and follow next.
Here are the operations we'll implement, animated on the list [8, 3, 15, 6]:
The class
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, values=()):
self.head = None
for v in reversed(values):
self.head = Node(v, self.head)
def __str__(self):
out, node = [], self.head
while node:
out.append(str(node.value))
node = node.next
return "[" + ", ".join(out) + "]"
def lowest(self):
node, low = self.head, self.head.value
while node:
if node.value < low:
low = node.value
node = node.next
return low
def insert(self, index, value):
if index == 0:
self.head = Node(value, self.head)
return
prev = self.head
for _ in range(index - 1): # walk to the node *before* the position
prev = prev.next
prev.next = Node(value, prev.next)
def delete(self, value):
if self.head and self.head.value == value:
self.head = self.head.next
return True
prev = self.head
while prev and prev.next:
if prev.next.value == value:
prev.next = prev.next.next # bypass the node
return True
prev = prev.next
return False
def reverse(self):
prev, node = None, self.head
while node:
nxt = node.next # remember the rest of the list
node.next = prev # turn this link around
prev, node = node, nxt
self.head = prev
lst = LinkedList([8, 3, 15, 6])
print("start: ", lst, "lowest:", lst.lowest())
lst.insert(2, 11)
print("insert 11 at 2:", lst)
print("delete 15:", lst.delete(15), lst)
lst.reverse()
print("reverse: ", lst)
print("delete 42:", lst.delete(42), lst)start: [8, 3, 15, 6] lowest: 3
insert 11 at 2: [8, 3, 11, 15, 6]
delete 15: True [8, 3, 11, 6]
reverse: [6, 11, 3, 8]
delete 42: False [6, 11, 3, 8]
The printed lists match the animation's frames after each operation.
Insert: walk to the predecessor
To insert at position i, walk to node i - 1 and splice the new node in after it. The order of the two link updates matters: the new node must grab prev.next before prev.next is overwritten. Inserting at position 0 is the special case where there is no predecessor and the head changes.
Delete: bypass the node
Deleting means making the predecessor skip over the node: prev.next = prev.next.next. Python's garbage collector frees the unreachable node. Again, deleting the head is a special case.
Reverse in place
Reversal walks the list once and turns every link around. Three variables are enough: the reversed part so far (prev), the current node, and the rest of the list (nxt). Let's print the state at each step:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def values(node):
out = []
while node:
out.append(node.value)
node = node.next
return out
head = Node(1, Node(2, Node(3, Node(4))))
prev, node = None, head
while node:
nxt = node.next
node.next = prev
prev, node = node, nxt
print(f"reversed part {values(prev)}, rest {values(node)}")
head = prev
print(values(head))reversed part [1], rest [2, 3, 4]
reversed part [2, 1], rest [3, 4]
reversed part [3, 2, 1], rest [4]
reversed part [4, 3, 2, 1], rest []
[4, 3, 2, 1]
Detecting a cycle: the tortoise and the hare
If a bug (or a deliberate design) makes some node point back to an earlier node, the list loops forever. Floyd's cycle detection uses two pointers: slow moves one step at a time, fast moves two. If there is a cycle, fast eventually laps slow and they meet; if there is none, fast reaches the end. It needs only O(1) extra memory.
class Node:
def __init__(self, value):
self.value = value
self.next = None
def has_cycle(head):
slow = fast = head
steps = 0
while fast and fast.next:
slow = slow.next
fast = fast.next.next
steps += 1
if slow is fast:
return True, steps
return False, steps
nodes = [Node(v) for v in range(6)]
for a, b in zip(nodes, nodes[1:]):
a.next = b
print("straight list:", has_cycle(nodes[0]))
nodes[-1].next = nodes[2] # 5 points back to 2: a loop
print("with a loop: ", has_cycle(nodes[0]))straight list: (False, 3)
with a loop: (True, 4)
Finding the middle node
The same two-speed idea finds the middle in one pass: when fast reaches the end, slow is halfway.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.value
def build(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
print(middle(build([10, 20, 30, 40, 50])))
print(middle(build([10, 20, 30, 40])))30
30
For an even length this returns the second of the two middle nodes.
Summary of costs
| Operation | Time | Notes |
|---|---|---|
| Traverse / find / lowest | O(n) |
|
| Insert or delete at the head | O(1) |
|
Insert or delete at position i |
O(i) to walk there, then O(1) |
|
| Reverse | O(n) time, O(1) memory |
|
| Cycle detection (Floyd) | O(n) time, O(1) memory |
Test yourself
When inserting new after node prev, which order of assignments is correct?
prev.next = newthennew.next = prev.nextnew.next = prev.nextthenprev.next = new- Either order works
new.next = prevthenprev.next = new
In Floyd's cycle detection, how fast do the two pointers move?
- Both one step
- One step and two steps
- Two steps and three steps
- One goes forward, one backward
How much extra memory does in-place reversal of a linked list need?
- O(1)
- O(log n)
- O(n)
- O(n²)