Sub topic 6
Reversal, Middle Node, and Cycle Detection
Assume you know singly linked lists, object references, loops, and Big-O notation. A node stores data and a reference named next to the next node. The last node points to None.
Reversing a singly linked list
To reverse a list, redirect every next reference toward the previous node. Keep three references:
prev: the part already reversedhead: the node currently being processednxt: the original next node, saved before changinghead.next
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def reverse(head):
prev = None
while head is not None:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
def values(head):
result = []
while head is not None:
result.append(head.data)
head = head.next
return result
head = Node(1, Node(2, Node(3)))
head = reverse(head)
print(values(head)) # [3, 2, 1]The old head becomes the last node, and the returned prev becomes the new head. The algorithm takes O(n) time and O(1) extra space.
Finding the middle node
Use two references:
slowmoves one node at a time.fastmoves two nodes at a time.
When fast reaches the end, slow is at the middle. For an even-length list, this version returns the second middle node.
def middle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
return slowThis uses O(n) time and O(1) extra space. Do not count nodes first unless you need a specific middle convention.
Detecting a cycle
A cycle exists if following next references can return to a previously visited node. Floyd’s cycle detection algorithm uses the same slow and fast references. If a cycle exists, the faster reference eventually catches the slower one.
def has_cycle(head):
slow = fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseUse identity comparison, such as is, rather than comparing node data. Different nodes can contain equal data.
| Task | Time | Extra space |
|---|---|---|
| Reverse list | O(n) | O(1) |
| Find middle | O(n) | O(1) |
| Detect cycle | O(n) | O(1) |
Exercise
What does middle return for a four-node list containing 1, 2, 3, and 4?
Show answer
It returns the node containing 3, because slow moves one step while fast moves two steps.