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.

PythonData Integrity

Code

pythonsnippet
43 lines
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: None

Tortoise 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

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.