php实现栈
栈的基本概念
栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。核心操作包括:

- push:元素入栈。
- pop:元素出栈(返回并移除栈顶元素)。
- peek:查看栈顶元素(不移除)。
- isEmpty:检查栈是否为空。
PHP数组实现栈
PHP数组天然支持栈操作,通过 array_push() 和 array_pop() 函数即可实现:

$stack = [];
// 入栈
array_push($stack, "A");
array_push($stack, "B");
// 出栈
$top = array_pop($stack); // 返回 "B"
// 查看栈顶
$peek = end($stack); // 返回 "A"
// 检查是否为空
$isEmpty = empty($stack); // false
面向对象封装
通过类封装栈操作,增强可复用性:
class Stack {
private $stack = [];
public function push($item) {
array_push($this->stack, $item);
}
public function pop() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return array_pop($this->stack);
}
public function peek() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return end($this->stack);
}
public function isEmpty() {
return empty($this->stack);
}
}
// 使用示例
$stack = new Stack();
$stack->push("X");
$stack->push("Y");
echo $stack->pop(); // 输出 "Y"
性能优化实现
若需高频操作栈,避免函数调用开销,可直接操作数组:
class OptimizedStack {
private $stack = [];
private $count = 0;
public function push($item) {
$this->stack[$this->count++] = $item;
}
public function pop() {
if ($this->count === 0) {
throw new RuntimeException("Stack is empty");
}
return $this->stack[--$this->count];
}
}
应用场景
- 函数调用栈:PHP内部维护的调用栈。
- 括号匹配:检查表达式中的括号是否成对。
- 回溯算法:如路径搜索、撤销操作。
通过以上方法,可灵活实现栈结构并根据需求选择实现方式。





