版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014204761/article/details/82939390
def hasCycle(self, head):
"""
注意边界越界的问题
设置一个快指针和慢指针,慢指针和快指针相遇就存在环,如果有存在节点的next为None的情况没有环。
"""
if not head:
return False
if not head.next or not head.next.next:
return False
s = head.next
f = head.next.next
while f and s:
if f == s:
return True
elif not f.next or not s.next:###边界越界
return False
else:
s = s.next
f = f.next.next
return False
leetcode 142
def detectCycle(self, head):
"""
在141基础上先判断是否存在环(快慢指针)
如果存在环,继续把快指针=head,快指针走一步,继续走下去,直到相遇点就是环的入口点
"""
if not head:
return None
if not head.next or not head.next.next:
return None
s = head.next
f = head.next.next
flag = 0
while f and s:
if f == s:
break
elif not f.next or not s.next:###边界越界
return None
else:
s = s.next
f = f.next.next
'''
边界条件注意
'''
if s == f and f.next:
f = head
while f != s:
s = s.next
f = f.next
return f
return None
为什么是快指针是慢指针的两倍速度,为什么入口点是相遇之后放慢快指针再次相遇的点,参考
https://blog.csdn.net/xy010902100449/article/details/48995255