Sub topic 3
Slow and Fast Pointers in Linked Lists
Assume you know Python classes, references, loops, and basic Big-O notation. This chapter builds on singly linked-list traversal.
Slow and fast pointers
A slow pointer moves one node at a time. A fast pointer moves two nodes at a time. Comparing their positions helps solve problems without storing every visited node.
The technique uses constant extra space, or O(1) space. It is useful for finding cycles and locating the middle node. A common error is advancing fast without first checking both fast and fast.next.
Doubly linked lists
A doubly linked list stores two references in each node:
nextpoints forward.prevpoints backward.
This allows traversal in both directions and removal in O(1) time when you already have the target node. The cost is extra memory and more links to maintain. Every insertion or deletion must update both neighboring nodes.
Circular linked lists
In a circular linked list, the last node points back to the first node instead of None. A circular list can be singly or doubly linked. It suits repeated rounds, such as turn-based scheduling.
Because there is no None endpoint, traversal must stop after a known number of steps or when it reaches the starting node again.
Detecting a cycle with Floyd's algorithm
Floyd's cycle-detection algorithm starts slow and fast at the head. If the list has a cycle, fast eventually catches slow. If fast reaches None, there is no cycle.
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 FalseMerging two sorted lists
To merge sorted lists, compare their current nodes, attach the smaller one, and advance that list. A dummy node avoids special handling for the first result node. The operation takes O(n + m) time and O(1) extra space.
Where linked lists are used
Linked lists are useful when nodes move frequently and the program already has a reference to an insertion or deletion position. Arrays usually provide faster indexing and better memory locality, so they are often the better default.
Exercise
Why can Floyd's algorithm detect a cycle without storing visited nodes?
Show answer
The fast pointer eventually laps the slow pointer inside a cycle, while it reaches None in an acyclic list.