標籤:資料結構 隊列 php
<?phpclass 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; }}
本文出自 “一切皆有可能” 部落格,請務必保留此出處http://noican.blog.51cto.com/4081966/1600889
資料結構之隊列——鏈式儲存結構(php代碼實現)