PHP to find the link in the list of the Ring entry node detailed steps

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.