快慢指针:
class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: # 如果链表为空或者只有一个节点,肯定不存在环 if not head or not head.next: return False # 初始化慢指针和快指针 slow = head fast = head.next # 开始循环,直到快指针达到链表末尾 while slow and fast and fast.next: # 如果慢指针和快指针相遇,说明存在环 if slow == fast: return True # 移动慢指针一步 slow = slow.next # 移动快指针两步 fast = fast.next.next # 如果循环结束仍未找到相遇点,说明链表中不存在环 return False
标签:head,slow,leedcode,fast,next,链表,环形,指针 From: https://www.cnblogs.com/yyyjw/p/18039279