PHP 实现循环队列

循环队列的概念
循环队列是一种线性数据结构,其操作基于先进先出(FIFO)原则。与普通队列不同,循环队列通过将队列的尾部和头部连接起来,形成一个环形结构,从而更高效地利用存储空间。

循环队列的实现思路
- 固定大小的数组:使用数组存储队列元素,并维护两个指针(front 和 rear)分别指向队列的头部和尾部。
- 模运算:通过模运算实现指针的循环移动,避免数组越界。
- 判空与判满:通过 front 和 rear 的关系判断队列是否为空或已满。
PHP 实现代码
以下是一个完整的 PHP 循环队列实现:
class CircularQueue {
private $queue;
private $front;
private $rear;
private $size;
private $capacity;
public function __construct($capacity) {
$this->capacity = $capacity;
$this->queue = array_fill(0, $capacity, null);
$this->front = -1;
$this->rear = -1;
$this->size = 0;
}
public function enqueue($item) {
if ($this->isFull()) {
return false;
}
if ($this->isEmpty()) {
$this->front = 0;
}
$this->rear = ($this->rear + 1) % $this->capacity;
$this->queue[$this->rear] = $item;
$this->size++;
return true;
}
public function dequeue() {
if ($this->isEmpty()) {
return null;
}
$item = $this->queue[$this->front];
$this->queue[$this->front] = null;
if ($this->front == $this->rear) {
$this->front = -1;
$this->rear = -1;
} else {
$this->front = ($this->front + 1) % $this->capacity;
}
$this->size--;
return $item;
}
public function isEmpty() {
return $this->size == 0;
}
public function isFull() {
return $this->size == $this->capacity;
}
public function getSize() {
return $this->size;
}
public function peek() {
if ($this->isEmpty()) {
return null;
}
return $this->queue[$this->front];
}
}
使用示例
$queue = new CircularQueue(3);
$queue->enqueue(1);
$queue->enqueue(2);
$queue->enqueue(3);
echo $queue->dequeue(); // 输出 1
$queue->enqueue(4);
echo $queue->peek(); // 输出 2
关键点说明
- 初始化:构造函数中设置队列容量,并初始化数组和指针。
- 入队(enqueue):检查队列是否已满,更新 rear 指针并插入元素。
- 出队(dequeue):检查队列是否为空,返回 front 指针指向的元素并更新指针。
- 判空与判满:通过 size 变量或 front/rear 指针的关系判断队列状态。
通过这种方式,可以高效地实现循环队列的基本操作。






