1. 程式人生 > >php連結串列筆記:連結串列的檢測

php連結串列筆記:連結串列的檢測

<?php
/**
 * Created by PhpStorm.
 * User: huizhou
 * Date: 2018/12/2
 * Time: 11:48
 */

/**
 * 連結串列的檢測
 * Class CheckCirclesList
 */

/**
 * 單鏈表類
 */
class Node{
    private $next;
    private $value;

    public function __construct($value = null)
    {
        $this->value = $value
; } public function getValue(){ return $this->value; } public function setValue($value){ $this->value = $value; } public function getNext(){ return $this->next; } public function setNext($next){ $this->next
= $next; } } /** * 找出帶環連結串列的環的入口結點 * @param Node $pHead * @return Node */ function entryNodeOfLoop(Node $pHead){ $slow = $pHead; $fast = $pHead; while ($fast != null && $fast->getNext() !=null ){ /** 單鏈表中環的檢測 首先設定兩個指標,分別命名為fast和slow,fast指標每次向後移2步,slow指標每次向後移1步。 如果,fast指標最後走到尾結點,則沒有環。 如果,fast指標和slow指標相遇,則證明有環。 *
*/ $slow = $slow->getNext(); // 慢指標走一步 $fast = $fast->getNext()->getNext(); // 快指標走兩步 // 快慢指標環內相遇 if($slow === $fast){ // 快指標回到頭結點 $fast = $pHead; // 同一速度再同時走 while ($slow != $fast){ $slow = $slow->getNext(); $fast = $fast->getNext(); } /** 環的起始結點的查詢 當fast與slow相遇之後, fast指標從頭結點開始走,每次走1步 當fast再次與slow相遇以後,相遇處的結點為環的入口結點 **/ // 兩個相遇的點一定是環的入口 if ($slow == $fast){ return $fast; } } } } function test(){ // 建立一個帶環的連結串列 $linkList = new Node(); $temp = $linkList; $node1 = new Node('1'); $temp->setNext($node1); $temp = $node1; $node2 = new Node('2'); $temp->setNext($node2); $temp = $node2; $node3 = new Node('3'); $temp->setNext($node3); $temp = $node3; $node4 = new Node('4'); $temp->setNext($node4); $node4->setNext($node2); // 尾節點指向第二個節點 //列印環 var_dump($linkList); //列印入口節點 $result = entryNodeOfLoop($linkList); var_dump($result); } test();