/**
* 第三种——循环顺序队列的实现方法
* 此方法是解决前两种方法的缺点,利用循环队列的方法达到了最优时间复杂度和空间复杂度
*
*
*/
class SqQueue3{
const ARR_MAX=20;
private $SqArr;
private $front;
private $rear;
//初始化队列
public function __construct(){
$this->SqArr=array();
$this->front=0;
$this->rear=0;
}
//销毁队列
public function DestroyQueue(){
$this->SqArr=null;
$this->front=$this->rear=0;
}
//清空队列
public function ClearQueue(){
$this->SqArr=array();
$this->front=$this->rear=0;
}
//队列是否为空
public function QueueEmpty(){
if($this->front==$this->rear){
return 'Null';
}else{
return 'No Null';
}
}
//队列的长度
public function QueueLength(){
return ($this->rear - $this->front + self::ARR_MAX) % self::ARR_MAX;
}
//取得队头元素
public function GetHead(){
if($this->rear==$this->front){
return 'ERROR';
}
return $this->SqArr[$this->front];
}
//从队尾掺入元素
public function EnQueue($elem){
$tail=($this->rear + 1)%self::ARR_MAX;//如果此值等于头元素说明队列已满
if($tail == $this->front){
return 'ERROR';
}
$this->SqArr[$this->rear]=$elem;
$this->rear=($this->rear+1)%self::ARR_MAX;
return 'OK';
}
//从队头删除元素
public function DeQueue(){
if($this->rear==$this->front){
return 'ERROR';
}
unset($this->SqArr[$this->front]);
$this->front=($this->front + 1)%self::ARR_MAX;
return 'OK';
}
//遍历队元素
public function QueueTraverse(){
$arr=array();
for($i=0;$i<:arr_max>
if(isset($this->SqArr[$i])){
$arr[]=$this->SqArr[$i];
}
}
return $arr;
}
//或者
public function QueueTraverse2(){
$arr=array();
$i=$this->front;
while($i != $this->rear){
$arr[]=$this->SqArr[$i];
$i=($i+1)%self::ARR_MAX;
}
return $arr;
}
}