我使用两个堆栈编写了堆栈的实现和队列的部分实现。除了一件事之外,几乎一切都按预期工作。对于某些问题,当我var_dump dequeue的结果时,它返回NULL,当我在dequeue中var_dump结果时,它返回一个预期的布尔值。任何人都可以解释来自哪里的差异?
<?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 :(得分:1)
由于您正在使用递归,因此需要在第二个if块中返回该值。
do {
...
}
while ($this->stack1->isEmpty() === false);
return $this->dequeue();
答案 1 :(得分:1)
createArray()
客户端/调用代码不会看到do
{
$pop = $this->stack1->pop();
$this->stack2->push($pop);
}
while ($this->stack1->isEmpty() === false);
$this->dequeue();
(上面)的结果,因为由于递归,您将(至少)两个级别(已删除)客户/调用代码。这就是您在客户端/调用代码中获得null结果的原因。