php 实现栈
实现栈的基本概念
栈是一种遵循后进先出(LIFO)原则的数据结构,核心操作包括压栈(push)、弹栈(pop)、查看栈顶元素(peek)和判断栈是否为空(isEmpty)。
使用数组实现栈
PHP 数组天然支持栈操作,可通过内置函数直接实现:
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 $this->stack[count($this->stack) - 1];
}
// 检查栈是否为空
public function isEmpty() {
return empty($this->stack);
}
}
手动实现栈(不依赖 array_push/pop)
通过维护索引模拟栈行为,适合理解底层逻辑:
class ManualStack {
private $stack = [];
private $top = -1;
public function push($item) {
$this->stack[++$this->top] = $item;
}
public function pop() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return $this->stack[$this->top--];
}
public function peek() {
if ($this->isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return $this->stack[$this->top];
}
public function isEmpty() {
return $this->top === -1;
}
}
栈的应用示例
验证括号匹配是栈的典型应用场景:
function isBalanced($expression) {
$stack = new Stack();
$pairs = [')' => '(', '}' => '{', ']' => '['];
for ($i = 0; $i < strlen($expression); $i++) {
$char = $expression[$i];
if (in_array($char, ['(', '{', '['])) {
$stack->push($char);
} elseif (in_array($char, [')', '}', ']'])) {
if ($stack->isEmpty() || $stack->pop() != $pairs[$char]) {
return false;
}
}
}
return $stack->isEmpty();
}
// 示例
echo isBalanced("({[]})") ? "Valid" : "Invalid"; // 输出 Valid
性能注意事项
- PHP 的
array_push/pop时间复杂度为 O(1),适合大多数场景。 - 手动实现方式在极端大数据量时可能需优化内存管理。
- 栈的容量可通过添加
$maxSize属性限制,并在push时检查。







