php 循环队列,队列和循环队列-php数组
//實現(xiàn)基本隊列
class Queues
{
private $head;
private $tail;
private $cnt; //數(shù)組大小
private $array = [];
public function __construct($n = 5)
{
$this->cnt = $n;
$this->head = 0;
$this->tail = 0;
}
//數(shù)組實現(xiàn)隊列
public function basisEnQueue($val)
{
//隊列已滿
if ($this->tail == $this->cnt) {
return false;
}
$this->array[$this->tail] = $val;
$this->tail++;
return true;
}
//出隊列
public function basisDelQueue()
{
//隊列為空
if ($this->head == $this->tail) {
return false;
}
$ret = $this->array[$this->head];
unset($this->array[$this->head]);
$this->head++;
return $ret;
}
//隊列遷移 使用已刪除空間
public function migrationEnQueue($val)
{
//隊列已滿
if ($this->tail == $this->cnt) {
//tail ==n && head==0,表示整個隊列都占滿了
if ($this->head == 0) {
return false;
}
for ($i = $this->head; $i < $this->tail; $i++) {
$this->array[$i - $this->head] = $this->array[$i];
unset($this->array[$i]);
}
$this->tail = $this->tail - $this->head;
$this->head = 0;
}
$this->array[$this->tail] = $val;
$this->tail++;
return true;
}
}
$q = new Queues();
$q->basisEnQueue('a');
$q->basisEnQueue('b');
$q->basisEnQueue('c');
$q->basisEnQueue('d');
$q->basisEnQueue('f');
$r1 = $q->basisDelQueue();
$r2 = $q->basisDelQueue();
// $q->migrationEnQueue('g');
// var_dump($q);exit;
//循環(huán)隊列
class CircularQueue
{
private $head;
private $tail;
private $cnt; //數(shù)組大小
private $array = [];
public function __construct($n = 5)
{
$this->cnt = $n;
$this->head = 0;
$this->tail = 0;
}
public function enqueue($val)
{
//(tail+1)%n=head 隊列滿的時候
if (($this->tail + 1) % $this->cnt == $this->head) {
return false;
}
$this->array[$this->tail] = $val;
$this->tail = ($this->tail + 1) % $this->cnt;
return true;
}
public function dequeue()
{
//如果head == tail 表示隊列為空
if ($this->head == $this->tali) {
return false;
}
$ret = $this->array[$this->head];
unset($this->array[$this->head]);
$this->head = ($this->head + 1) % $this->cnt;
return $ret;
}
}
$c = new CircularQueue;
$c->enqueue('a');
$c->enqueue('b');
$c->enqueue('c');
var_dump($c);exit;
總結(jié)
以上是生活随笔為你收集整理的php 循环队列,队列和循环队列-php数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬虫什么网站都能爬吗_pyt
- 下一篇: 流水灯c语言实验报告心得,嵌入式流水灯实