1.開辟字典,有額外空間
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
dict1={}
if not head or not head.next:
return False
count=-1
while head and head not in dict1:
count+=1
dict1[head]=count
if head.next:
head = head.next
else:
return False
return True
2.快慢指針,沒有額外空間
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
quick=slow=head
# 下邊這個循環(huán)不用擔(dān)心死循環(huán),因為只要出現(xiàn)環(huán),就會被if語句捕捉,不會永遠轉(zhuǎn)下去的
# 若無環(huán),當快指針遍歷到最后時,就會結(jié)束循環(huán)
while quick.next and quick.next.next:
quick=quick.next.next
slow=slow.next
if quick==slow:
return True
return False