PHP implementation to find out the list of links in the link list of the entry node detailed

Source: Internet
Author: User
This paper mainly introduces the implementation of PHP to find the link list of the entry node, involving PHP for the loop chain list of the traversal, find, calculation and other related operational skills, the need for friends can refer to, hope to help everyone.

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;} 

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.