hash表方法
class Solution:
def hasCycle(self , head: ListNode) -> bool:
nodes=set()
while head:
if head in nodes:
return True
else:
nodes.add(head)
head=head.next
return False
快慢指针方法
class Solution:
def hasCycle(self , head: ListNode) -> bool:
slow=head
fast=head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if slow==fast:
return True
return False