class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 用于判断给定链表是否存在环 def hasCycle(head): if not head or not head.next: return False slow = head fast = head.next while slow != fast: if not fast or not fast.next: return False slow = slow.next fast = fast.next.next return True