使用遞迴函式實現棧的逆序, 不使用其他資料結構 stack reverse
阿新 • • 發佈:2018-12-11
* 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::getAndRemoveLastElement($this); $this->reverse(); $this->push($i); } private static function getAndRemoveLastElement(Stack $stack) { $result = $stack->pop(); if ($stack->isEmpty()) { return $result; } $last = self::getAndRemoveLastElement($stack); $stack->push($result); return $last; } }
* 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