php使用佇列 php實現佇列

2021-10-22 22:50:36 字數 2914 閱讀 7373

佇列(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 3

echo php_eol;

echo php_eol;

echo $a->dequeue(); //輸出 1 佇列 2 3

echo php_eol;

echo php_eol;

echo $a->dequeue(); //輸出 2 佇列 3

$a->enqueue(5); //佇列 3 5

echo php_eol;

echo php_eol;

$a->outputqueue(); //輸出 3 5

$a->clearqueue(); //佇列空;

php使用佇列 PHP佇列用法例項

什麼是佇列,是先進先出的線性表,在具體應用中通常用鍊錶或者陣列來實現,佇列只允許在後端進行插入操作,在前端進行刪除操作。什麼情況下會用了佇列呢,併發請求又要保證事務的完整性的時候就會用到佇列,當然不排除使用其它更好的方法,知道的不仿說說看。佇列還可以用於減輕資料庫伺服器壓力,我們可以將不是即時資料放...

php實現佇列

雙向佇列的實現 class doubleendedqueue public function push element public function pop public function inject element public function eject 例項化該類,測試下 a new d...

php使用佇列 PHP使用兩個棧實現佇列功能的方法

問題用兩個棧來實現乙個佇列,完成佇列的push和pop操作。佇列中的元素為int型別。解決思路 兩個棧。出棧的時候,如果棧2不為空,就出棧2。如果棧2為空,就把棧1的出棧再入棧2。實現 arr1 array arr2 array function mypush node array push arr...