//实现基本队列
class Queues
{
private $head;
private $tail;
private $cnt; //数组大小
private $array = [];
public function __construct($n = 5)
{
$this->cnt = $n;
$this->head = 0;
$this->tail = 0;
}
//数组实现队列
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;
//循环队列
class CircularQueue
{
private $head;
private $tail;
private $cnt; //数组大小
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;
来源:oschina
链接:https://my.oschina.net/hackdebug/blog/3211398