链式存储结构 php,数据结构之队列――链式存储结构(php代码实现)

class QNode{

public  $data;

public  $next;

public function __construct($data){

$this->data=$data;

$this->next=null;

}

}

class LinkQueue{ //链队列包含头结点,实例化时,此队列为空

private $data;

private $next;

private $front;//指向头结点

private $rear;//指向尾结点

//    private $length;

public function __construct(){

$this->data=null;

$this->next=null;

$this->front=$this; //指向头结点

$this->rear=$this;//指向头结点

//        $this->length=0;

}

//销毁队列

public function DestroyQueue(){

while($this->front){ //销毁首先是从头结点开始

$this->rear=$this->front->next;

unset($this->front);

$this->front=$this->rear;

}

}

//清空队列

public function ClearQueue(){

$p=$this->front->next;

while($p){

$q=$p->next;

unset($p);

$p=$q;

}

$this->front->next=null;

$this->rear=$this->front;

}

//队列是否为空

public function QueueEmpty(){

if($this->front==$this->rear){

return 'Null';

}else{

return 'No Null';

}

}

//队列的长度

public function QueueLength(){

$p=$this->front;

$i=0;

while($p != $this->rear){

$i++;

$p=$p->next;

}

return $i;

//        return $this->length;

}

//取得队头元素

public function GetHead(){

if($this->front==$this->rear){

return 'ERROR';

}

return $this->front->next->data;

}

//从队尾插入元素

public function EnQueue(){

$node=new QNode(mt_rand(100,200));

$node->next=$this->rear->next;

$this->rear->next=$node;

$this->rear=$node;

$this->length++;

}

//从队头删除元素

public function DeQueue(){

if($this->front==$this->rear){

return 'ERROR';

}

$p=$this->front->next;

unset($this->front->next);

$this->front->next=$p->next;

if($this->rear==$p){ //如果只有一个元素那么,为指针就需要变化了。

$this->rear=$this->front;

}

$this->length--;

return 'OK';

}

//遍历队列元素

public function QueueTraverse(){

if($this->front==$this->rear){

return 'ERROR';

}

$arr=array();

$p=$this->front->next;

while($p){

$arr[]=$p->data;

$p=$p->next;

}

return $arr;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值