# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
slow = head # 不能写slow=fast=head,因为head = [1,2], pos=-1时会出错
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next # 慢指针每次前进1步
fast = fast.next.next #快指针每次前进2步
return True #存在环,快慢指针相遇