当前位置:首页 > 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
分享给朋友:

相关文章

php redis实现消息队列

php redis实现消息队列

使用 PHP 和 Redis 实现消息队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如列表(List)、发布/订阅(Pub/Sub)等,非常适合实现消息队列。以下是几种常见的实现方式…

PHP http长连接的实现

PHP http长连接的实现

HTTP 长连接基础概念 HTTP长连接(Keep-Alive)允许在单个TCP连接上发送和接收多个HTTP请求/响应,减少重复建立和断开连接的开销。HTTP/1.1默认启用长连接,而HTTP/1.0…

php实现一个双向队列

php实现一个双向队列

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

php使用redis实现队列

php使用redis实现队列

PHP 使用 Redis 实现队列 Redis 是一个高性能的键值存储系统,支持多种数据结构,如字符串、哈希、列表、集合等。利用 Redis 的列表(List)数据结构可以轻松实现队列功能。以下是实现…

php redis如何实现队列

php redis如何实现队列

PHP Redis 实现队列的方法 Redis 是一个高性能的键值存储系统,常用于实现队列功能。以下是在 PHP 中使用 Redis 实现队列的几种常见方法: 使用 LPUSH 和 RPOP 实现队…

PHP实现会员管理

PHP实现会员管理

PHP实现会员管理的方法 数据库设计 创建会员表(members)包含字段:id(主键)、username、password(建议加密存储)、email、register_time、last_logi…