法一: class Solution: def hasCycle(self, head: ListNode) -> bool: a = set() while head: if head in a: return True a.add(head) head = head.next return False 法二: class Solution: def hasCycle(self, head: ListNode) -> bool: slow = fast = head # if not head: # 没必要这样写可以加入while循环判断更简洁 # return False while fast and fast.next: # 防止head为空和出现空指针的next的情况 slow = slow.next fast = fast.next.next if slow is fast: return True return False