php实现栈结构
PHP实现栈结构
栈是一种遵循后进先出(LIFO)原则的数据结构。PHP中可以通过数组或SplStack类实现栈的功能。
使用数组实现栈
PHP数组本身支持栈操作,通过array_push和array_pop函数即可实现:
$stack = [];
// 入栈操作
array_push($stack, 'A');
array_push($stack, 'B');
array_push($stack, 'C');
// 出栈操作
$top = array_pop($stack); // 返回'C'
$top = array_pop($stack); // 返回'B'
使用SplStack类
PHP标准库(SPL)提供了专门的SplStack类:
$stack = new SplStack();
// 入栈操作
$stack->push('A');
$stack->push('B');
$stack->push('C');
// 出栈操作
$top = $stack->pop(); // 返回'C'
$top = $stack->pop(); // 返回'B'
自定义栈类实现
如需更多控制,可以创建自定义栈类:
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(10);
$stack->push(20);
echo $stack->pop(); // 输出20
性能考虑
数组实现的栈在PHP中性能良好,因为数组操作是PHP的核心功能。SplStack提供了更多面向对象的方法,适合需要严格栈行为的场景。自定义实现则提供了最大的灵活性。







