当前位置:首页 > PHP

PHP 实现循环队列

2026-02-15 08:59:15PHP

循环队列的概念

循环队列是一种线性数据结构,通过数组实现,利用头尾指针的循环移动来避免数据搬移,提高空间利用率。当队列尾部到达数组末尾时,会从数组头部重新开始存储。

PHP 实现循环队列

PHP 实现循环队列的关键点

  • 使用固定大小的数组存储元素。
  • 维护两个指针 frontrear,分别指向队首和队尾。
  • 通过取模运算实现指针的循环移动。
  • 区分队列满和队列空的条件。

代码实现

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

    public function __construct($capacity) {
        $this->capacity = $capacity + 1; // 预留一个空位用于区分满和空
        $this->queue = array_fill(0, $this->capacity, null);
        $this->front = 0;
        $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;
    }

    // 获取队首元素
    public function peek() {
        if ($this->isEmpty()) {
            throw new RuntimeException("Queue is empty");
        }
        return $this->queue[$this->front];
    }

    // 获取队列大小
    public function size() {
        return ($this->rear - $this->front + $this->capacity) % $this->capacity;
    }
}

使用示例

$queue = new CircularQueue(3);
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
echo $queue->dequeue(); // 输出 1
$queue->enqueue(4);
echo $queue->size();    // 输出 3

注意事项

  • 循环队列的容量通常需要预留一个空位,以区分队列满和队列空的条件。
  • 入队和出队操作需检查队列状态,避免溢出或下溢。
  • 指针移动通过取模运算实现循环特性。

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

相关文章

react实现消息队列

react实现消息队列

实现消息队列的基本思路 在React中实现消息队列通常需要结合状态管理工具(如Redux、Context API)或自定义Hook来管理消息的存储、消费和清理。消息队列的核心功能包括消息的入队、出队、…

php实现一个双向队列

php实现一个双向队列

PHP 实现双向队列 双向队列(Deque)是一种允许在队列两端进行插入和删除操作的线性数据结构。PHP 可以通过数组或 SplDoublyLinkedList 类实现双向队列。 使用数组实…

PHP实现图文聊天

PHP实现图文聊天

PHP实现图文聊天的方法 数据库设计 创建数据库表存储聊天消息,包含字段如消息ID、发送者ID、接收者ID、消息内容、消息类型(文本/图片)、发送时间等。使用MySQL或其他数据库管理系统。 CRE…

拼团 PHP实现

拼团 PHP实现

拼团功能 PHP 实现 拼团是一种常见的电商营销模式,允许用户邀请好友一起购买商品,达到指定人数后享受优惠价格。以下是使用 PHP 实现拼团功能的关键步骤和代码示例。 数据库设计 拼团功能通常需要设…

PHP实现excel

PHP实现excel

PHP 实现 Excel 操作 读取 Excel 文件 使用 PHP 读取 Excel 文件可以通过 PhpSpreadsheet 库实现。安装该库可以通过 Composer: composer r…

PHP实现建站

PHP实现建站

PHP建站的基本步骤 安装PHP环境 使用XAMPP、WAMP或MAMP等集成环境快速搭建本地开发环境,这些工具包含Apache、MySQL和PHP。对于生产环境,推荐使用LNMP(Linux+Ngi…