2015-08-30 162 views
0

我用兩個堆棧編寫了這個堆棧實現和部分實現隊列。除了一件事之外,幾乎所有事情都按預期工作對於某些問題,當我var_dump出隊的結果,它返回NULL,當我var_dump結果出隊內部它返回一個布爾值如預期。任何人都可以解釋從哪裏來的差異?PHP對象訪問問題

<?php 


class stack 
{ 
    private $stack = array(); 
    function push($value) 
    { 
     $this->stack[] = $value; 
    } 

    function pop() 
    { 
     if ($this->isEmpty()) 
      throw new RunTimeException("Stack is empty"); 
     $top = $this->stack[count($this->stack)-1]; 
     unset($this->stack[count($this->stack)-1]); 
     $this->stack = array_values($this->stack); 
     return $top; 
    } 
    function isEmpty() 
    { 
     return empty($this->stack) ? true : false; 
    } 
    function peak() 
    { 
     $top = $this->stack[count($this->stack)]; 
     return $top; 
    } 
    function printr() 
    { 
     print_r($this->stack); 
    } 
} 



class queue 
{ 
    function __construct() 
    { 
     $this->stack1 = new Stack(); 
     $this->stack2 = new Stack(); 
    } 

    function push($value) 
    { 
     $this->stack1->push($value); 
    }  

    function dequeue() 
    { 
     if (!$this->stack2->isEmpty()) 
     { 
      $this->stack2->printr(); 
      $pop = $this->stack2->pop(); 
      var_dump($pop); 
      return $pop; 
     } 
     else if (!$this->stack1->isEmpty()) 
     { 
      do 
      { 
       $pop = $this->stack1->pop(); 
       $this->stack2->push($pop); 
      } 
      while ($this->stack1->isEmpty() === false); 
      $this->dequeue(); 
     } 
     else 
     { 
      throw new RunTimeException("Queue is empty"); 
     } 

    } 
    function isEmpty() 
    { 
     if (($this->stack1->isEmpty()) AND ($this->stack2->isEmpty())) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
    function peak() 
    { 

    } 
} 


$myQueue = new queue(); 
$myQueue->push(1); 
$myQueue->push(2); 
var_dump($myQueue->dequeue()); 
+0

'?真:假 - 「你爲什麼這樣做?空已經返回一個布爾值 – ThiefMaster

+0

你是完全正確的。對於那個很抱歉。 – user1029829

回答

1

由於您使用的是遞歸,所以您需要在第二個if塊中返回該值。

do { 
    ... 
} 
while ($this->stack1->isEmpty() === false); 
return $this->dequeue(); 
+0

工作正常!謝謝! – user1029829

1
do 
{ 
    $pop = $this->stack1->pop(); 
    $this->stack2->push($pop); 
} 
while ($this->stack1->isEmpty() === false); 
$this->dequeue(); 

客戶機/調用代碼將不會看到的$this->dequeue()(以上)的結果,因爲,由於遞歸,你將(至少)兩級下來從客戶端(刪除)/調用代碼。這就是爲什麼你在客戶端/調用代碼中得到空結果的原因。