php 循环队列,队列和循环队列-php数组

//实现基本队列

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值