Tortoise And Hare Detect List Cycles
Slow and fast pointers meet inside a cycle; resetting one to the head and walking again at equal speed lands on the entry node.
Code
class Node:
def __init__(self, value, next=None):
self.value, self.next = value, next
def build(values, tail_to=None):
nodes = [Node(v) for v in values]
for node, nxt in zip(nodes, nodes[1:]):
node.next = nxt
if nodes and tail_to is not None:
nodes[-1].next = nodes[tail_to] # 制造环:尾巴指回中间节点
return nodes[0] if nodes else None
def has_cycle(head):
# 快慢指针:有环则二者必然在环内相遇
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
def cycle_entry(head):
# 相遇后把一个指针放回头部,同速前进,再次相遇即入环点
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
slow = head
while slow is not fast:
slow, fast = slow.next, fast.next
return slow
return None
linear = build(['a', 'b', 'c', 'd'])
looped = build(['a', 'b', 'c', 'd'], tail_to=1)
print('linear:', has_cycle(linear))
print('looped:', has_cycle(looped), '-> entry value:', cycle_entry(looped).value)
print('linear entry:', cycle_entry(linear))Output
Captured from a sandboxed run of this snippet in the build pipeline.
linear: False
looped: True -> entry value: b
linear entry: NoneTortoise And Hare Detect List Cycles: reading the source
Tortoise And Hare Detect List Cycles reduces to the class Node and the functions __init__, build, has_cycle and cycle_entry.
The file repeats itself only inside for node, nxt in zip(nodes, nodes[1:]).
What to watch for
- The file imports nothing at all; the language runtime covers every call it makes.
Using it
Signature: def build(values, tail_to=None)
Output markers, as printed: linear:, looped:, linear entry:.
Treat build as the API: import it, and ignore the supporting code.
Key statements
def __init__(self, value, next=None):
self.value, self.next = value, next
def build(values, tail_to=None):
nodes = [Node(v) for v in values]
for node, nxt in zip(nodes, nodes[1:]):
node.next = nxt
if nodes and tail_to is not None:
nodes[-1].next = nodes[tail_to] # 制造环:尾巴指回中间节点
return nodes[0] if nodes else None
def has_cycle(head):
# 快慢指针:有环则二者必然在环内相遇
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `__init__`, `build`, `has_cycle` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.