思路:
使用快、慢两个指针以不同的速度遍历链表,若块指针能再次遇到慢指针,则链表中存在环
代码:
In [1]: class Node:
...: def __init__(self, value, next=None):
...: self.value = value
...: self.next = next
...:
In [2]: def has_cycle(node):
...: slow, fast = node, node
...: while fast and fast.next:
...: slow = slow.next
...: fast = fast.next.next
...: if slow == fast:
...: return True
...: return False
...:
In [3]: node6 = Node(6)
...: node5 = Node(5, node6)
...: node4 = Node(4, node5)
...: node3 = Node(3, node4)
...: node2 = Node(2, node3)
...: node1 = Node(1, node2)
In [4]: has_cycle(node1)
Out[4]: False
In [5]: node6.next = node3
...: has_cycle(node1)
Out[5]: True