如果有環(huán),那么一快(2步)一慢(1步),總會在環(huán)的某個位置相遇,這個時候,快指針比慢指針多走了n圈,因為快指針可能走了很多圈,慢指針還沒進(jìn)圈。設(shè)環(huán)的長度為b,則有f = 2s,f = s+nb,s = nb
另外,指針從開始走到入口,需要的步數(shù)假設(shè)是a,以后每次再到達(dá)入口走的次數(shù)是a+nb
。
現(xiàn)在慢指針已經(jīng)走了nb步了,再走a步即可再次到達(dá)入口處,因此需要一個讓慢指針走a步的控制方法。
我們再設(shè)一指針,讓其從開始走到入口,同時慢指針也繼續(xù)走就能同時到入口處了。
代碼如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersect(self, head):
#這個函數(shù)負(fù)責(zé)尋找,快慢指針第一次相遇的位置
tortoise = head
hare = head
while hare is not None and hare.next is not None:
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
return tortoise
return None
def detectCycle(self, head):
if head is None:
return None
intersect = self.getIntersect(head)
if intersect is None:
return None
#如果有環(huán)的話,就把新的節(jié)點設(shè)在頭部,和原來相遇的節(jié)點每次向前走一步,相遇的地方就是環(huán)的入口
ptr1 = head
ptr2 = intersect
while ptr1 != ptr2:
ptr1 = ptr1.next
ptr2 = ptr2.next
return ptr1