標籤:php 簡單 struct 迴圈隊列 empty enqueue 隊列 最大 this
隊列(Queue): 滿足先進先出(FIFO)的規則;
下面使用php實現一個簡單的迴圈隊列模型;
初始狀態的隊列,隊列長度為0,隊頭和隊尾的指標相同均位於隊列的開始;
入隊操作:隊尾指標向後移動,長度加一;
出隊操作:隊頭指標向後移動,長度減一;
迴圈隊列特點:隊列大小固定,隊列所開闢的記憶體空間可迴圈使用,指標的移動是靠與queueSize取餘運算移動;
下面的例子是利用數組實現佇列儲存體,數組下標作為指標;
<?php/** * Class Queue */class Queue{ /** * @var int 隊頭指標 */ private $_front; /** * @var int 隊尾指標 */ private $_rear; /** * @var array 隊列數組 */ private $_queue; /** * @var int 隊列實際長度 */ private $_queueLength; /** * @var int 隊列容量; */ private $_queueSize; /** * Queue constructor.初始化隊列 * @param int $capacity 容量(迴圈隊列的最大長度) */ public function __construct($size) { $this->_queue = []; $this->_queueSize = $size; $this->_front = 0; $this->_rear = 0; $this->_queueLength = 0; } /** * 銷毀隊列; */ public function __destruct() { unset($this->_queue); } /** * @method 入隊 * @param mixed $elem 入隊的元素 * @return bool */ public function enQueue($elem) { if (!$this->isFull()) { $this->_queue[$this->_rear] = $elem; $this->_rear++; $this->_rear = $this->_rear % $this->_queueCapacity; $this->_queueLength++; return true; } return false; } /** * @method 出隊 * @return mixed|null */ public function deQueue() { if (!$this->isEmpty()) { $elem = $this->_queue[$this->_front]; //unset($this->_queue[$this->_front]); $this->_front++; $this->_front %= $this->_queueCapacity; $this->_queueLength--; return $elem; } return null; } /** * @method 判斷隊列是否為空白; * @return bool */ public function isEmpty() { return $this->_queueLength === 0; } /** * @method 判斷隊列是否飽和; * @return bool */ public function isFull() { return $this->_queueLength === $this->_queueCapacity; } /** * @method 遍曆隊列並輸出(測試隊列) */ public function outputQueue() { for ($i = $this->_front; $i < $this->_queueLength + $this->_front; $i++) { echo $this->_queue[$i % $this->_queueCapacity].PHP_EOL; } } /** * @method 清空隊列 */ public function clearQueue() { $this->_queue = []; $this->_front = 0; $this->_rear = 0; $this->_queueLength = 0; }}
測試隊列類,講道理是沒什麼大問題的,最佳化就靠真實的業務情境了;
$a = new Queue(3);echo ‘enQueue1 $a->enQueue(1)‘.PHP_EOL;$a->enQueue(1);echo ‘enQueue2 $a->enQueue(2)‘.PHP_EOL;$a->enQueue(2);echo ‘enQueue3 $a->enQueue(3)‘.PHP_EOL;$a->enQueue(3);echo ‘enQueue4 $a->enQueue(4)‘.PHP_EOL;$a->enQueue(4); //講道理是失敗的;$a->outputQueue(); //輸出 1 2 3echo PHP_EOL;echo PHP_EOL;echo $a->deQueue(); //輸出 1 隊列 2 3echo PHP_EOL;echo PHP_EOL;echo $a->deQueue(); //輸出 2 隊列 3$a->enQueue(5); //隊列 3 5echo PHP_EOL;echo PHP_EOL;$a->outputQueue(); //輸出 3 5$a->clearQueue(); //隊列空;
如有不對,敬請指教
資料結構隨筆-php實現隊列