php 实现栈
栈的基本概念
栈是一种遵循后进先出(LIFO)原则的数据结构,主要操作包括压栈(push)和弹栈(pop)。在 PHP 中,可通过数组或类实现栈的功能。
方法一:使用 PHP 数组模拟栈
PHP 数组原生支持栈操作,结合 array_push 和 array_pop 函数即可实现:
$stack = [];
// 压栈操作
array_push($stack, "A");
array_push($stack, "B");
// 弹栈操作
$topElement = array_pop($stack); // 返回 "B"
关键点

array_push向数组末尾添加元素(压栈)。array_pop移除并返回数组末尾元素(弹栈)。- 可通过
end($stack)查看栈顶元素而不移除。
方法二:通过类封装栈
通过面向对象的方式封装栈操作,提高代码复用性和可读性:
class Stack {
private $elements = [];
// 压栈
public function push($item) {
array_push($this->elements, $item);
}
// 弹栈
public function pop() {
if ($this->isEmpty()) {
throw new RuntimeException("栈为空");
}
return array_pop($this->elements);
}
// 获取栈顶元素
public function peek() {
if ($this->isEmpty()) {
throw new RuntimeException("栈为空");
}
return end($this->elements);
}
// 检查栈是否为空
public function isEmpty() {
return empty($this->elements);
}
// 获取栈大小
public function size() {
return count($this->elements);
}
}
// 使用示例
$stack = new Stack();
$stack->push("X");
$stack->push("Y");
echo $stack->pop(); // 输出 "Y"
优势

- 封装内部实现细节,避免直接操作数组。
- 提供异常处理,增强健壮性。
方法三:SplStack 标准库
PHP 的 SplStack 是标准库提供的栈实现,基于双向链表,性能更优:
$stack = new SplStack();
// 压栈
$stack->push("C");
$stack->push("D");
// 弹栈
echo $stack->pop(); // 输出 "D"
// 其他操作
$stack->rewind(); // 重置指针
while ($stack->valid()) {
echo $stack->current(); // 遍历元素
$stack->next();
}
特点
- 支持迭代和指针操作。
- 无需手动实现,直接调用内置方法。
性能与选择建议
- 简单场景:使用数组 +
array_push/array_pop。 - 复杂项目:优先选择
SplStack或自定义类,便于扩展和维护。 - 注意:PHP 数组的栈操作时间复杂度为 O(1),但动态扩容可能偶尔触发性能开销。






