弗洛伊德循环检测算法又称 “龟兔赛跑 ”算法,是一种检测链表中循环或循环的常用技术。
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def has_cycle(head):
if not head or not head.next:
return False # No cycle with fewer than two nodes
slow = head
fast = head
while fast and fast.next:
slow = slow.next # Move one step
fast = fast.next.next # Move two steps
if slow == fast:
return True # Cycle detected
return False # No cycle found
# Example usage:
# Create a linked list with a cycle
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
head.next = node2
node2.next = node3
node3.next = node4
node4.next = node2 # Cycle back to node2
print("Has cycle:", has_cycle(head)) # Should print "Has cycle: True"
