《php循环队列代码》
一、解决方案
在PHP中实现循环队列,可以解决普通线性队列空间利用率不高的问题。通过将存储空间看作是一个首尾相接的圆环,当队尾指针到达数组末尾时又回到数组开头继续存储元素,从而充分利用存储空间。
二、基于数组的循环队列实现
php
class CircleQueue{
private $queue = array(); // 存储队列元素的数组
private $front; // 队头指针
private $rear; // 队尾指针
private $maxSize; // 容量</p>
<pre><code>public function __construct($size){
$this->maxSize = $size;
$this->front = 0;
$this->rear = 0;
for($i = 0;$i < $size;$i++){
$this->queue[$i] = null;
}
}
// 入队操作
public function enQueue($data){
if(($this->rear + 1) % $this->maxSize == $this->front){
echo "队列已满n";
return false;
}
$this->queue[$this->rear] = $data;
$this->rear = ($this->rear + 1) % $this->maxSize;
return true;
}
// 出队操作
public function deQueue(){
if($this->rear == $this->front){
echo "队列为空n";
return false;
}
$data = $this->queue[$this->front];
$this->queue[$this->front] = null;
$this->front = ($this->front + 1) % $this->maxSize;
return $data;
}
// 获取队列长度
public function getLength(){
return ($this->rear - $this->front + $this->maxSize) % $this->maxSize;
}
// 打印队列元素
public function showQueue(){
if($this->rear == $this->front){
echo "队列为空n";
return;
}
for($i = $this->front;$i != $this->rear;$i = ($i + 1) % $this->maxSize){
echo $this->queue[$i]." ";
}
echo "n";
}
}
三、基于对象数组构建循环队列(另一种思路)
我们可以创建一个节点类来表示队列中的元素,然后再构建循环队列。
```php
class Node{
public $data;
public $next;
public function __construct($data){
$this->data = $data;
$this->next = null;
}
}
class CircleQueueByNode{
private $head; // 指向头结点
private $tail; // 指向尾结点
private $maxSize; // 容量
private $count; // 当前元素个数
public function __construct($size){
$this->maxSize = $size;
$this->head = new Node(null);
$this->tail = $this->head;
$this->tail->next = $this->head;
$this->count = 0;
}
// 入队
public function enQueue($data){
if($this->count == $this->maxSize){
echo "队列已满n";
return false;
}
$newNode = new Node($data);
$this->tail->next = $newNode;
$this->tail = $newNode;
$this->tail->next = $this->head;
$this->count++;
return true;
}
// 出队
public function deQueue(){
if($this->count == 0){
echo "队列为空n";
return false;
}
$data = $this->head->next->data;
$temp = $this->head->next;
$this->head->next = $temp->next;
if($this->count == 1){
$this->tail = $this->head;
}
unset($temp);
$this->count--;
return $data;
}
// 获取队列长度
public function getLength(){
return $this->count;
}
// 显示队列元素
public function showQueue(){
if($this->count == 0){
echo "队列为空n";
return;
}
$p = $this->head->next;
while(true){
echo $p->data." ";
$p = $p->next;
if($p == $this->head){
break;
}
}
echo "n";
}
}
```
这两种思路都可以实现循环队列,在实际应用中可以根据具体需求选择合适的方式。例如,如果需要频繁地随机访问队列中的元素,种基于数组的方式可能更方便;而第二种基于对象数组的方式对于某些链表操作场景可能会更加灵活。