class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
法一:设置一个快指针,一个慢指针
如果有环则必有fast==slow
"""
slow=fast=head
while slow and fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
return True
return False
"""
法二:设置一个nodes=set()
同理可以用一个字典也行key:node,value:0
hash_table = {} # key = node, value = pos
x, pos = head, 0
while x is not None:
if x in hash_table:
return True
else:
hash_table[x] = pos
x = x.next
else:
return False
遍历,如果有环则必有节点在node里面
"""
def hasCycle(self, head):
nodes = set()
while head is not None:
if head in nodes:
return True
else:
nodes.add(head)
head = head.next
return False