To a linked list, wherein if the ring comprises, find the entry ring node list, otherwise, outputs null.
Links: https://www.nowcoder.com/questionTerminal/253d2c59ec3e4bc68da16833f79a38e4
Source: Cattle-off network
Fast setting speed pointer and slow, the fast speed of the pointer is twice slower pointer
When the speed of the pointer met:
At this time, the pointer's journey is slow Sslow = x + m * c + a
fast pointer's journey to + n-X * = Sfast C + A
2 Sslow Sfast =
2 * (m * X + C + A) = (X + n * c + a)
can be deduced:
X = (n-- 2 * m) C * - a
= (n-- 2 * m -1) * C + C - a
i.e. the front ring = number of distance rings the length (as possibly 0) + c - a
what is c - a? This is the meeting point, the distance (from orange) cycloalkyl rear portion and x (red distance) is equal to
class Solution: def EntryNodeOfLoop(self, pHead): # write code here if pHead==None or pHead.next==None or pHead.next.next==None: return None # 一快一慢 low=pHead.next fast=pHead.next.next # 如果有环,两者会相遇 while low!=fast: if fast.next==None or fast.next.next==None: return None low=low.next FAST = fast.next.next # position to encounter the distance ring starting from the inlet and the inlet to the same ring FAST = PHEAD the while Low =! FAST: Low = low.next FAST = fast.next return FAST