php实现堆栈
堆栈的基本概念
堆栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。主要操作包括压栈(push)和弹栈(pop),其他常见操作有查看栈顶元素(peek)和判断栈是否为空。

使用数组实现堆栈
PHP的数组原生支持堆栈操作,通过array_push()和array_pop()函数即可实现:
$stack = [];
// 压栈操作
array_push($stack, "A");
array_push($stack, "B");
array_push($stack, "C");
// 弹栈操作
$top = array_pop($stack); // 返回"C"
自定义堆栈类实现
通过面向对象的方式封装堆栈操作,提供更清晰的接口:
class Stack {
private $elements = [];
public function push($item) {
array_push($this->elements, $item);
}
public function pop() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return array_pop($this->elements);
}
public function peek() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
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"
堆栈的应用场景
- 函数调用栈:PHP内部使用堆栈管理函数调用
- 表达式求值:处理括号匹配、后缀表达式等
- 撤销操作:记录操作历史实现撤销功能
- 深度优先搜索:图算法中的非递归实现
性能注意事项
- PHP数组的
array_push()和array_pop()时间复杂度均为O(1) - 对于大规模数据,考虑使用SplStack(SPL库提供的堆栈实现)
- 避免在循环中频繁进行堆栈操作,可能影响性能







