欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > php >内容正文

php

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

发布时间:2024/7/5 php 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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;

总结

以上是生活随笔为你收集整理的php 循环队列,队列和循环队列-php数组的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。