当前位置:首页 > PHP

php环行队列实现

2026-02-16 03:00:15PHP

环形队列的实现原理

环形队列(Circular Queue)是一种基于数组的先进先出(FIFO)数据结构,通过维护头尾指针实现循环利用空间。当尾部到达数组末尾时,会绕回到数组开头,避免普通队列的假溢出问题。

环形队列的关键操作

初始化
定义队列大小、头指针(front)、尾指针(rear)和存储数组。初始时 frontrear 均为 0。

入队(enqueue)
检查队列是否已满,若未满则将元素放入 rear 位置,并更新 rear = (rear + 1) % capacity

出队(dequeue)
检查队列是否为空,若不为空则取出 front 位置的元素,并更新 front = (front + 1) % capacity

判空与判满

php环行队列实现

  • 空队列条件:front == rear
  • 满队列条件:(rear + 1) % capacity == front(需预留一个空位避免歧义)

PHP 实现代码示例

class CircularQueue {
    private $queue;
    private $front;
    private $rear;
    private $capacity;

    public function __construct($size) {
        $this->capacity = $size + 1; // 预留一个空位
        $this->queue = array_fill(0, $this->capacity, null);
        $this->front = $this->rear = 0;
    }

    public function enqueue($item) {
        if ($this->isFull()) {
            throw new RuntimeException("Queue is full");
        }
        $this->queue[$this->rear] = $item;
        $this->rear = ($this->rear + 1) % $this->capacity;
    }

    public function dequeue() {
        if ($this->isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        $item = $this->queue[$this->front];
        $this->front = ($this->front + 1) % $this->capacity;
        return $item;
    }

    public function isEmpty() {
        return $this->front == $this->rear;
    }

    public function isFull() {
        return ($this->rear + 1) % $this->capacity == $this->front;
    }
}

// 使用示例
$queue = new CircularQueue(3);
$queue->enqueue(1);
$queue->enqueue(2);
echo $queue->dequeue(); // 输出 1
$queue->enqueue(3);

注意事项

  • 数组大小需为 实际容量 + 1,以区分空和满的状态。
  • 指针更新时使用取模运算实现环形逻辑。
  • 实际应用中可扩展动态扩容功能,但需重新分配数组并调整指针。

性能分析

  • 时间复杂度:入队和出队均为 O(1)。
  • 空间复杂度:O(n),n 为队列容量。

标签: 队列php
分享给朋友:

相关文章

php实现

php实现

PHP 实现的基本方法 PHP 是一种服务器端脚本语言,广泛用于 Web 开发。以下是 PHP 实现的一些常见方法。 变量与数据类型 PHP 变量以 $ 开头,支持多种数据类型: $nam…

php实现登录

php实现登录

PHP 登录功能实现 数据库连接与用户表创建 创建一个数据库连接文件 db.php,用于管理数据库连接。MySQL 示例代码如下: <?php $host = 'localhost'; $db…

php购物车实现

php购物车实现

PHP购物车实现方法 使用PHP实现购物车功能可以通过多种方式完成,以下是几种常见的实现方法: Session存储购物车数据 利用PHP的$_SESSION超全局变量存储购物车数据是最简单的方法。用…

php怎么实现登录功能

php怎么实现登录功能

数据库准备 创建用户表存储登录信息,通常包括用户名、密码(需加密)等字段。示例SQL: CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY…

php实现博客

php实现博客

使用PHP实现博客系统 数据库设计 创建数据库表存储博客文章和用户信息。常见的表包括posts(文章)和users(用户)。 CREATE TABLE users ( id INT AUTO…

php 实现类

php 实现类

PHP 类的基本实现 在 PHP 中,类通过 class 关键字定义,后跟类名和一对花括号。类名通常遵循大驼峰命名法(如 ClassName)。以下是基本语法: class ClassName {…