方法1:哈希表,空间复杂度O(n)
方法2:快慢指针,龟兔赛跑
# 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:
#时间复杂度O(1),龟兔赛跑
if not head or not head.next: return False
fast = head.next
slow = head
while slow != fast:
if not fast or not fast.next: return False
slow = slow.next
fast = fast.next.next
return True
'''
#时间复杂度O(n)
seen = set()
while head:
if head in seen: return True
else: seen.add(head)
head = head.next
return False
'''