This article explains the PHP implementation to find the link in the list of the entry node of the ring.
A linked list contains the ring, please find the link to the list of the entry node.
Solution Ideas
The first step is to find the loop in the meeting point. Using P1,P2 to point to the list head, p1 each step, p2 each walk two steps, until P1==P2 find the meeting point in the ring.
Step two, find the entrance to the ring. The next step, when P1==p2, p2 through the number of nodes is 2x,p1 through the number of nodes X, set the ring has n nodes, p2 than P1 walk a circle has 2x=n+x; N=x, can see P1 actually walked a ring step number, then let P2 point to the list head, P1 position unchanged, p1,p2 every step until p1==p2; At this point the P1 points to the inlet of the ring. (I don't know yet)
Implementation code
/*class listnode{var $val; var $next = NULL, function __construct ($x) {$this->val = $x;}} */function Entrynodeofloop ($pHead) {if ($pHead = = NULL | | $pHead->next = = null) return null; $p 1 = $pHead; $p 2 = $pHea D while ($p 2!=null && $p 2->next!=null) {$p 1 = $p 1->next; $p 2 = $p 2->next->next;if ($p 1 = = $p 2) {$p 2 = $pHea D;while ($p 1!= $p 2) $p 1 = $p 1->next; $p 2 = $p 2->next; } if ($p 1 = = $p 2) return $p 1; }} return null; }
This article explains PHP implementation to find the link list in the Portal node, more relevant content please focus on the PHP Chinese web.