← 中文资源

简体中文版本

龟兔指针检测链表环

快慢指针同速赛跑:有环必在环内相遇,无环则 fast 先走到头;相遇后把慢指针放回头部同速前进,再遇即入环点。线性表返回 False 与 None。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

linear: False
looped: True -> entry value: b
linear entry: None

实现说明

逻辑集中在类 Node和函数 __init__、build、has_cycle、cycle_entry里。 迭代发生在 for node, nxt in zip(nodes, nodes[1:]) 内部——循环之外的语句只执行一遍。

使用要点

  • 演示输出是带标签的(linear:、looped:、linear entry:),每个操作都会留下自己的一行标注。
  • 把 build 当作 API:导入它,其余代码可以忽略。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 __init__、build、has_cycle。

主签名形如 def build(values, tail_to=None)

核心语句

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

代码示例

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))