【题目描述】
【代码思路】这是一道快慢指针的经典应用,快慢指针从头指针出发,快指针每次走两步,慢指针每次走一步,假设链表中非环部分长度为F,环部分长度为C,那么只要有环存在,快慢指针经过C次迭代会相遇,再从相遇点起走F步可找到环的入口点。这种做法时间复杂度是O(n),空间复杂度O(1)。
【源代码】
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p=head
if head==None:return None
slow=head
fast=head
while(fast):
if fast.next==None:
return None
fast=fast.next.next
slow=slow.next
if slow==fast:
break
while(fast!=p):
if fast==None:
return None
p=p.next
fast=fast.next
return fast
复制代码
转载于:https://juejin.im/post/5d088250e51d455ca0436254