当前位置:首页 > PHP

php 实现栈

2026-02-14 16:20:58PHP

实现栈的基本概念

栈是一种遵循后进先出(LIFO)原则的数据结构,核心操作包括压栈(push)、弹栈(pop)、查看栈顶元素(peek)和判断栈是否为空(isEmpty)。

php 实现栈

使用数组实现栈

PHP 数组天然支持栈操作,可通过内置函数直接实现:

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 时检查。

标签: php
分享给朋友:

相关文章

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现异步

php实现异步

PHP 实现异步的方法 PHP 本身是同步执行的脚本语言,但可以通过以下方法模拟异步操作或实现异步效果: 使用多进程(pcntl_fork) 通过 pcntl_fork 创建子进程实现异步,适用于…

php实现文件的下载

php实现文件的下载

PHP 实现文件下载的方法 在 PHP 中实现文件下载功能通常需要设置正确的 HTTP 头信息,并输出文件内容。以下是几种常见的实现方式: 使用 header() 函数强制下载 通过设置 Conte…

php 函数实现

php 函数实现

PHP 函数实现基础 PHP 函数的定义使用 function 关键字,后跟函数名和参数列表。函数名不区分大小写,但建议保持一致。 function functionName($param1, $p…

php数组实现

php数组实现

PHP 数组的基本实现 PHP 数组是一种非常灵活的数据结构,可以存储多个值,并且支持多种类型的键(整数或字符串)。PHP 数组实际上是有序映射(ordered map),可以看作是列表(vector…

无限分类实现 php

无限分类实现 php

无限分类的实现方法 无限分类通常用于构建多层级结构的数据,如商品分类、部门架构等。以下是几种常见的实现方式: 邻接列表模式(Adjacency List) 邻接列表是最简单的实现方式,通过在每个记录…