本文目录导读:

在 PHP 中实现栈(Stack)数据结构,有几种常见方法:
使用数组(最常用)
// 初始化栈
$stack = [];
// 入栈(push)
array_push($stack, "A");
array_push($stack, "B");
array_push($stack, "C");
// 出栈(pop)
$last = array_pop($stack); // 返回 "C"
// 查看栈顶元素(peek)
$top = end($stack); // 返回 "B"
// 检查栈是否为空
if (empty($stack)) {
echo "栈为空";
}
// 获取栈大小
$size = count($stack); // 返回 2
使用 SplStack(SPL 标准库)
// 创建栈
$stack = new SplStack();
// 入栈
$stack->push("A");
$stack->push("B");
$stack->push("C");
// 出栈
$last = $stack->pop(); // 返回 "C"
// 查看栈顶
$top = $stack->top(); // 返回 "B"
// 检查是否为空
if ($stack->isEmpty()) {
echo "栈为空";
}
// 栈大小
$size = $stack->count();
// 迭代栈(从栈顶到栈底)
foreach ($stack as $item) {
echo $item . "\n";
}
自定义栈类(面向对象)
class Stack {
private $elements = [];
// 入栈
public function push($element) {
array_push($this->elements, $element);
}
// 出栈
public function pop() {
if ($this->isEmpty()) {
throw new UnderflowException("Cannot pop from an empty stack");
}
return array_pop($this->elements);
}
// 查看栈顶
public function peek() {
if ($this->isEmpty()) {
return null;
}
return end($this->elements);
}
// 检查是否为空
public function isEmpty() {
return empty($this->elements);
}
// 获取大小
public function size() {
return count($this->elements);
}
// 清空栈
public function clear() {
$this->elements = [];
}
}
// 使用示例
$stack = new Stack();
$stack->push("A");
$stack->push("B");
$stack->push("C");
echo $stack->pop() . "\n"; // 输出 "C"
echo $stack->peek() . "\n"; // 输出 "B"
echo "栈大小: " . $stack->size() . "\n"; // 输出 "2"
典型应用场景
// 1. 括号匹配检查
function checkBrackets($string) {
$stack = new SplStack();
$brackets = ['(' => ')', '{' => '}', '[' => ']'];
for ($i = 0; $i < strlen($string); $i++) {
$char = $string[$i];
if (isset($brackets[$char])) {
$stack->push($char);
} elseif (in_array($char, $brackets)) {
if ($stack->isEmpty() || $brackets[$stack->pop()] != $char) {
return false;
}
}
}
return $stack->isEmpty();
}
// 2. 进制转换
function decimalToBinary($decimal) {
$stack = new SplStack();
while ($decimal > 0) {
$stack->push($decimal % 2);
$decimal = intdiv($decimal, 2);
}
$result = '';
while (!$stack->isEmpty()) {
$result .= $stack->pop();
}
return $result;
}
性能对比
- 数组方法:简单直观,适合大多数场景
- SplStack:内存效率更高,性能更优(特别是大量数据时)
- 自定义类:最灵活,可以根据需要添加额外功能
直接使用 array_push() 和 array_pop() 在大多数场景下已经足够,如果对性能有严格要求或需要处理大量数据,建议使用 SplStack。