這篇文章就大家帶來的內容是介紹PHP隊列是什麼?如何實現? (程式碼範例)。有一定的參考價值,有需要的朋友可以參考一下,希望對你們有幫助。
隊列是一種特殊的線性表,它只允許在表的前端,可以稱為front,進行刪除操作;而在表的後端,可以稱為rear進行插入操作。
佇列和堆疊一樣,是一種操作受限制的線性表,和堆疊不同之處在於:佇列是遵循「先進先出」原則,而堆疊遵循的是「先進後出」原則。
佇列進行插入操作的端稱為隊尾,進行刪除操作的稱為隊頭,只允許在隊尾進行插入操作,在隊頭進行刪除操作。
佇列的資料元素又稱為佇列元素,在隊尾中插入一個元素稱為入隊,在隊頭刪除一個元素稱為出隊。
具體實作參考代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | <?php
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 ( '0' => '队尾' );
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 --){
if ( $this ->queue[ $i ])unset( $this ->queue[ $i ]);
$this ->queue[ $i ]= $this ->queue[ $i -1];
}
$this ->queue[ $this ->rear+1]= new data( $data );
echo '入队成功!<br>' ;
}
}
public function OutQ(){
if ( $this ->QIsEmpty()) echo "队空不能出队!<br>" ;
else {
unset( $this ->queue[ $this ->front]);
$this ->front--;
echo "出队成功!<br>" ;
}
}
}
$q = new queue(3);
$q ->InQ( "小苗" );
$q ->InQ( '马帅' );
$q ->InQ( '溜冰' );
$q ->InQ( '张世佳' );
$q ->OutQ();
$q ->InQ( "周瑞晓" );
$q ->OutQ();
$q ->OutQ();
$q ->OutQ();
$q ->OutQ();
|
登入後複製
本案例中有兩個類別:
第一個是data類,用於實現資料的存放以及佇列元素的入隊出隊情況;
第二個是queue類,用於隊列元素的一些入隊出隊操作。
隊列中包含四個屬性:
front(隊列的頭部)
rear(隊列的尾部)
maxsize(隊列的長度,即隊列元素個數)
queue(存放所有已入隊隊列元素的物件)
場景說明:
1.初始化佇列時,產生一個佇列,傳入一個參數作為maxsize初始化隊列把隊尾rear設為0,隊頭front也設為0,此時queue中只有0號元素,並且rear和front都指向它。
2.入隊時,先需要判斷隊列是否已滿(front-rear == maxsize),如果已滿不可在插入,如果未滿則允許插入。插入時,front自增,然後依序讓隊列所有元素向前移動一位(讓出隊尾位置以便插入新元素),然後產生新的data物件插入到隊尾位置。
3.出隊時,判斷隊伍是否為空(front == rear),若為空時,無法出隊。若不為空時,刪除front指向的對象,且front自減,完成出隊。
運行結果如下:

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。更多相關影片教學推薦:PHP教學!
以上是PHP隊列是什麼?如何實現? (程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!