【发布时间】:2013-12-11 04:44:20
【问题描述】:
我想构建一个用 PHP 实现的堆栈。最初我有这个代码:
class Stack
{
protected $stack;
protected $limit;
public function __construct($limit = 10) {
// initialize the stack
$this->stack = array();
// stack can only contain this many items
$this->limit = $limit;
}
public function push($item) {
// trap for stack overflow
if (count($this->stack) < $this->limit) {
// prepend item to the start of the array
array_unshift($this->stack, $item);
} else {
throw new RunTimeException('Stack is full!');
}
}
public function pop() {
if ($this->isEmpty()) {
// trap for stack underflow
throw new RunTimeException('Stack is empty!');
} else {
// pop item from the start of the array
return array_shift($this->stack);
}
}
public function top() {
return current($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
}
然后用这个正常初始化类:
$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
这是正确的并且正在运行。但是,我想用这样的初始值初始化我的堆栈:
$stack = new Stack(array(1,2,3,4,5));
我该如何实现?
请注意,所有其他功能(例如 pop 和 push)都是正常的。
【问题讨论】:
-
仅供参考,PHP 有
array_push(php.net/manual/en/function.array-push.php) 和array_pop(us3.php.net/array_pop) 实现。 -
旁注:
$stack和$limit可以是private -
是的,但如果你有这些,它看起来会更整洁?
-
在 PHP 中显然也有更快、更完整的实现,请参阅php.net/manual/en/class.ds-stack.php。
标签: php data-structures stack