1. 程式人生 > >php鏈表筆記:鏈表的檢測

php鏈表筆記:鏈表的檢測

php 設置 node 節點 try 證明 head tor 兩個

<?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();

php鏈表筆記:鏈表的檢測