* Stack.php
<?php
/**
* Created by PhpStorm.
* User: Mch
* Date: 9/24/18
* Time: 9:30 AM
*/
namespace ds\stack;
class Stack extends \SplStack {
/**
* 使用递归函数实现栈的逆序, 不使用其他数据结构
*/
public function reverse() {
if ($this->isEmpty()) {
return;
}
$i = self::getAndRemoveBottom($this);
$this->reverse();
$this->push($i);
}
private static function getAndRemoveBottom(Stack $stack) {
$result = $stack->pop();
if ($stack->isEmpty()) {
return $result;
}
$bot = self::getAndRemoveBottom($stack);
$stack->push($result);
return $bot;
}
}
* index.php
<?php
include './Stack.php';
$stack = new \ds\stack\Stack();
for ($i = 0; $i < 5; $i++) {
$stack->push($i);
}
$stack->reverse();
while (!$stack->isEmpty()) {
echo $stack->pop().PHP_EOL;
}
* test
$ php index.php
0
1
2
3
4