PHP 資料結構隊列(SplQueue)和優先隊列(SplPriorityQueue)簡單使用執行個體_php執行個體

來源:互聯網
上載者:User
隊列這種資料結構更簡單,就像我們生活中排隊一樣,它的特性是先進先出(FIFO)。

PHP SPL中SplQueue類就是實現隊列操作,和棧一樣,它也可以繼承雙鏈表(SplDoublyLinkedList)輕鬆實現。
SplQueue類摘要如下:

SplQueue簡單使用如下:

複製代碼 代碼如下:
$queue = new SplQueue();

/**
* 可見隊列和雙鏈表的區別就是IteratorMode改變了而已,棧的IteratorMode只能為:
* (1)SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP (預設值,迭代後資料儲存)
* (2)SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE (迭代後資料刪除)
*/
$queue->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

//SplQueue::enqueue()其實就是 SplDoublyLinkedList::push()
$queue->enqueue('a');
$queue->enqueue('b');
$queue->enqueue('c');

//SplQueue::dequeue()其實就是 SplDoublyLinkedList::shift()
print_r($queue->dequeue());

foreach($queue as $item) {
echo $item . PHP_EOL;
}

print_r($queue);

而優先隊列SplPriorityQueue是基於堆(後文介紹)實現的。
SplPriorityQueue的類摘要如下:

SplPriorityQueue簡單使用:

$pq = new SplPriorityQueue(); $pq->insert('a', 10);$pq->insert('b', 1);$pq->insert('c', 8); echo $pq->count() .PHP_EOL; //3echo $pq->current() . PHP_EOL; //a /** * 設定元素出隊模式 * SplPriorityQueue::EXTR_DATA 僅提取值 * SplPriorityQueue::EXTR_PRIORITY 僅提取優先順序 * SplPriorityQueue::EXTR_BOTH 提取數組包含值和優先順序 */$pq->setExtractFlags(SplPriorityQueue::EXTR_DATA); while($pq->valid()) {  print_r($pq->current()); //a c b  $pq->next();}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.