队列(Queue),是一种特殊的先进先出线性表,其只能在前端进行删除操作(一般称为出队),在后端进行插入操作(一般称为入队)。下面学步园小编来讲解下PHP怎么实现队列?
PHP怎么实现队列
/**
*数据结构与算法(PHP实现)-队列(Queue)。
*
*@author创想编程(TOPPHP.ORG)
*@copyrightCopyright(c)2013创想编程(TOPPHP.ORG)AllRightsReserved
*@licensehttp://www.opensource.org/licenses/mit-license.phpMITLICENSE
*@version1.0.0-Build20130607
*/
classQueue{
/**
*队列。
*
*@vararray
*/
private$queue;
/**
*队列的长度。
*
*@varinteger
*/
private$size;
/**
*构造方法-初始化数据。
*/
publicfunction__construct(){
$this->queue=array();
$this->size=0;
}
/**
*入队操作。
*
*@parammixed$data入队数据。
*@returnobject返回对象本身。
*/
publicfunctionenqueue($data){
$this->queue[$this->size++]=$data;
return$this;
}
/**
*出队操作。
*
*@returnmixed空队列时返回FALSE,否则返回队头元素。
*/
publicfunctiondequeue(){
if(!$this->isEmpty()){
--$this->size;
$front=array_splice($this->queue,0,1);
return$front[0];
}
returnFALSE;
}
/**
*获取队列。
*
*@returnarray返回整个队列。
*/
publicfunctiongetQueue(){
return$this->queue;
}
/**
*获取队头元素。
*
*@returnmixed空队列时返回FALSE,否则返回队头元素。
*/
publicfunctiongetFront(){
if(!$this->isEmpty()){
return$this->queue[0];
}
returnFALSE;
}
PHP怎么实现队列
/**
*获取队列的长度。
*
*@returninteger返回队列的长度。
*/
publicfunctiongetSize(){
return$this->size;
}
/**
*检测队列是否为空。
*
*@returnboolean空队列则返回TRUE,否则返回FALSE。
*/
publicfunctionisEmpty(){
return0===$this->size;
}
}
?>
示例代码1
$queue=newQueue();
$queue->enqueue(1)->enqueue(2)->enqueue(3)->enqueue(4)->enqueue(5)->enqueue(6);
echo'
',print_r($queue->getQueue(),TRUE),'
';
$queue->dequeue();
echo'
',print_r($queue->getQueue(),TRUE),'
';
?>
说明:PHP数组函数已有类似队列的功能函数存在:array_unshift(入队)和、array_shift(出队)。
以上就是关于“PHP怎么实现队列”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!