当前位置:首页 > 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

判空与判满

  • 空队列条件: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实现验证码的方法 使用GD库生成验证码 GD库是PHP中处理图像的扩展,可用于生成验证码图片。 <?php session_start(); $width = 120; $height…

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="uploa…

php 登录实现

php 登录实现

PHP 登录实现 PHP 登录功能通常包括用户认证、会话管理和安全性措施。以下是实现 PHP 登录功能的关键步骤。 数据库准备 创建一个用户表存储用户信息,通常包括用户名、密码(加密存储)和其他必…

php怎么实现登录功能

php怎么实现登录功能

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

php 实现单链表

php 实现单链表

单链表的基本概念 单链表是一种线性数据结构,由节点组成,每个节点包含数据域和指向下一个节点的指针域。链表的头节点是访问整个链表的入口。 单链表的节点类实现 在PHP中,可以通过类来定义链表节…

php 实现类

php 实现类

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