队列:先进先出,是一个应用很广泛的数据结构,不管是存储还是消息,还是待执行任务等等,生活以及软件中使用的栗子比比皆是。


不多说直接上代码,参考多家,觉得这个是最符合中心思想的。为了区分是否满队列,我们还是j决定使用空一格是满的,示意图如下



直接上代码

//循环队列,顺序存储classqueue{private$data;private$front;private$rear;//定义最大容量constMAX=5;//定义数量//初始化队列,头指针和尾指针都只指向0,而且我们的满规定是空一个。function__construct(){$this->data=array();$this->front=0;$this->rear=0;echo"队列准备ok";}//一个有趣的小公式,因为我们规定中间间隔一个就是满了,原理和示意图用图片publicfunctionqueueLength(){echo($this->rear-$this->front+self::MAX)%self::MAX;}//入队列//没必要加入本队列参数,用$thispublicfunctioninQueue($e){if(($this->rear+1)%(self::MAX)==$this->front){echo'队列已经满了';die;}$this->data[$this->rear]=$e;$this->rear=($this->rear+1)%(self::MAX);echo'ok';}publicfunctiondeQueue(){if($this->front==$this->rear){echo'队列是空的';die;}//var$tmp;//$tmp=$this->data[$this->front]='';$this->front=($this->front+1)%self::MAX;//unset($this->data[$this->front]);echo'ok';}}

测试代码如下:

$obj=newqueue();$obj->inQueue(1);$obj->inQueue(2);var_dump($obj);$obj->deQueue();var_dump($obj);$obj->inQueue(3);var_dump($obj);$obj->inQueue(4);var_dump($obj);$obj->inQueue(5);var_dump($obj);$obj->deQueue();var_dump($obj);$obj->deQueue();var_dump($obj);$obj->deQueue();var_dump($obj);$obj->deQueue();var_dump($obj);$obj->queueLength();$obj->inQueue(1);var_dump($obj);$obj->inQueue(2);var_dump($obj);

有一首小诗我觉得作者写的很好,增加点文学气息



谢谢,愿法界众生,皆得安乐