首頁  >  文章  >  後端開發  >  PHP佇列演算法如何實作?

PHP佇列演算法如何實作?

不言
不言原創
2018-07-20 17:58:101460瀏覽

PHP實作佇列的方法是什麼?隊列是一種線性表,是按照先進先出的原則進行的,下面我們來看看本篇文章給大家介紹的一種PHP隊列演算法的實作。

此佇列演算法中有兩個類別一個是data類,這個類別是存放資料;第二個是queue也就是佇列類別這個就是佇列的一些操作。

首先隊列裡包含front(隊列的頭,也就是出隊是要出去的) rear(隊列的尾部在這裡永遠指向0) queue(存放所有入隊的data對象,queue中默認存在一個元素當空時front和rear都指向他) maxsize(隊列的長度)四個屬性

#應用說明:

1初始化隊列:產生一個隊列傳入一個參數作為maxsize初始化隊列把rear設為0 ,front設為0此時queue中只有0號元素rear和front都指向他

2.入隊:判斷隊列是否已滿(front-rear==maxsize),如果滿提示,若果沒滿先讓front 1,然後讓所有隊列中的元素像前移動一位(也就是給新來的讓出隊尾位置),然後生成data物件插入到隊尾1的位置。此時入隊成功!

3.出隊:判斷隊列是否為空(front==rear),如空提示,如不為空,刪除front指向的對象,front-1(向後移動一位),出隊成功!

<?php
/**
*  php队列算法
*  
*  Create On 2010-6-4
*  Author Been
*  QQ:281443751
*  Email:binbin1129@126.com
**/class data {    //数据
    private $data;    
    public function __construct($data){        
    $this->data=$data;        
    echo $data.":哥进队了!<br>";
    }    
    public function getData(){        
    return $this->data;
    }    public function __destruct(){        
    echo $this->data.":哥走了!<br>";
    }
}class queue{    protected $front;//队头
    protected $rear;//队尾
    protected $queue=array(&#39;0&#39;=>&#39;队尾&#39;);//存储队列
    protected $maxsize;//最大数
    
    public function __construct($size){        
    $this->initQ($size);
    }    //初始化队列
    private function initQ($size){        
    $this->front=0;        
    $this->rear=0;        
    $this->maxsize=$size;
    }    //判断队空
    public function QIsEmpty(){        
    return $this->front==$this->rear;
    }    //判断队满
    public function QIsFull(){        
    return ($this->front-$this->rear)==$this->maxsize;
    }    //获取队首数据
    public function getFrontDate(){        
    return $this->queue[$this->front]->getData();
    }    //入队
    public function InQ($data){        
    if($this->QIsFull())echo $data.":我一来咋就满了!(队满不能入队,请等待!)<br>";        
    else {            
    $this->front++;            
    for($i=$this->front;$i>$this->rear;$i--){                
    //echo $data;
                if($this->queue[$i])unset($this->queue[$i]);                
                $this->queue[$i]=$this->queue[$i-1];
            }            
            $this->queue[$this->rear+1]=new data($data);            
            //print_r($this->queue);
            //echo $this->front;
            echo &#39;入队成功!<br>&#39;;
        }
    }    //出队
    public function OutQ(){        
    if($this->QIsEmpty())echo "队空不能出队!<br>";        
    else{            
    unset($this->queue[$this->front]);            
    $this->front--;            
    //print_r($this->queue);
            //echo $this->front;
            echo "出队成功!<br>";
        }
    }
}$q=new queue(3);
$q->InQ("A");
$q->InQ(&#39;B&#39;);
$q->InQ(&#39;游泳&#39;);
$q->InQ(&#39;C&#39;);
$q->OutQ();
$q->InQ("D");
$q->OutQ();
$q->OutQ();
$q->OutQ();
$q->OutQ();

相關推薦:

PHP實作一個雙向佇列

#

以上是PHP佇列演算法如何實作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn