This time for everyone to bring PHP to find out the link in the list of links in the chain of steps in detail, PHP to find the link in the list of Ring entry node of the note, the following is the actual case, take a look.
Problem
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
<?php/*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 = $pHead; 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 = $pHead; 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;}
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP implementation from top to bottom print binary tree code share
PHP using the z-glyph sequence to print the binary tree steps