2016-08-04 42 views
1

以下是最簡單的形式我的類定義 -如何從鏈表的根節點中區分「僅有另一個節點」具有相同的值,同時檢查列表是否是循環的?

class Node 
{ 
    public $data; 
    public $next = null; 

    public function __construct($data) 
    { 
     $this->data = $data; 
    } 
} 

class LinkedList 
{ 
    public $root; 

//should have named checkIfCircular 
    public function checkIfCyclic() 
    { 
     $rootVal = $this->root->data; 
     $isCyclic = false; 

     //start iterating from the root, through the length of the ll and see if the root is encountered again. 
     $node = $this->root; 
     while($node->next!=null) 
     { 
      echo "<br>traversing ".$node->next->data." comparison ".($node->next === $this->root)." and ".($node->next == $this->root); 
      //case 2 -> strict comparison does not differentiate as expected here. Evaluates to true even in case of $ll2. 
      if($node->next === $this->root) 
      { 
       $isCyclic = true; 
       break; 
      } 
      else 
      { 
       $node=$node->next; 
      } 
     } 
     return $isCyclic; 
    } 
} 

以下是我如何初始化兩個鏈接列表 -

//3->4->5->6->first node 
$ll = new LinkedList(); 
$ll->root = new Node(3); 
$ll->root->next = new Node(4); 
$ll->root->next->next = new Node(5); 
$ll->root->next->next->next = new Node(6); 
$ll->root->next->next->next->next = $ll->root; 
echo "<br>see ll ".$ll->checkIfCyclic(); 


//3->4->5->6->3 (a different 3) 
$ll2 = new LinkedList(); 
$ll2->root = new Node(3); 
$ll2->root->next = new Node(4); 
$ll2->root->next->next = new Node(5); 
$ll2->root->next->next->next = new Node(6); 
$ll2->root->next->next->next->next = new Node(3); 
echo "<br>see ll2 ".$ll->checkIfCyclic(); 

以下是我的輸出 -

traversing 4 comparison and 
traversing 5 comparison and 
traversing 6 comparison and 
traversing 3 comparison 1 and 1 
see ll 1 
traversing 4 comparison and 
traversing 5 comparison and 
traversing 6 comparison and 
traversing 3 comparison 1 and 1 //I expected the 1st comparison to return false here 
see ll2 1 

我本來希望ll2能夠返回false。

然而,這個工程按照我的意料 -

$something = new Node(3); 
$another = $something; 
echo "compare same ".($something===$another)." and ".($something==$another)."<br>"; 

$something = new Node(3); 
$another = new Node(3); 
echo "compare different ".($something===$another)." and ".($something==$another)."<br>"; 

我缺少什麼?

回答

1

這是你的問題。你跟$ll而不是$ll2把它稱爲:

echo "<br>see ll2 ".$ll->checkIfCyclic(); 
+0

啊,我覺得自己躲在一個坑再次:d –

相關問題