Title Description
Thinking
The first step, to find sink ring relative speed with two pointers. Respectively slow
, fast
point to the head of the list, slow
each time step, fast
each take two steps, until the fast == slow
found phase sink in the ring.
The second step, to find the inlet ring. When fast == slow
, it is assumed slow
through the x nodes, the fast
through 2x nodes. Provided there are n nodes in the ring, since the fast
ratio of slow
multi-walk around (n nodes), it is the equation 2x = n + x
can be introduced n = x
, i.e., slow
in fact, a number of steps walked ring. At this time, we let fast
redirected the head of the list pHead
, slow
the same position, then slow
and fast
with every forward step, until fast == slow
, when two pointers meet the node is the entrance to the ring.
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def EntryNodeOfLoop(self, pHead): # write code here if pHead is None: return None if pHead.next is None: return None p = Pet q = pHead.next while p!=q: if q.next is not None and q.next.next is not None: p = p.next q = q.next.next else: break if p ==q: r = Pet p = p.next while r != p: r = r.next p = p.next return r else: return None