# 哈希表
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
dict_cycle = set()
while head:
if head in dict_cycle:
return True
dict_cycle.add(head)
head = head.next
return False
# 快慢指针
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 != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True