Home > Article > Backend Development > Simple usage examples of PHP data structure queue (SplQueue) and priority queue (SplPriorityQueue), priority queue data structure_PHP tutorial
Queue is a simpler data structure, just like queuing in our lives Likewise, its feature is first-in-first-out (FIFO).
The SplQueue class in PHP SPL implements queue operations. Like the stack, it can also be easily implemented by inheriting the SplDoublyLinkedList.
The SplQueue class summary is as follows:
SplQueue is simply used as follows:
Copy code The code is as follows:
$queue = new SplQueue();
/**
* It can be seen that the difference between queue and doubly linked list is that the IteratorMode has changed. The IteratorMode of the stack can only be:
* (1) SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP (default value, data is saved after iteration)
* (2) SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE (data deleted after iteration)
*/
$queue->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);
//SplQueue::enqueue() is actually SplDoublyLinkedList::push()
$queue->enqueue('a');
$queue->enqueue('b');
$queue->enqueue('c');
//SplQueue::dequeue() is actually SplDoublyLinkedList::shift()
print_r($queue->dequeue());
foreach($queue as $item) {
echo $item .PHP_EOL;
}
print_r($queue);
The priority queue SplPriorityQueue is implemented based on the heap (described later).
The class summary of SplPriorityQueue is as follows:
SplPriorityQueue is simple to use:
$pq = new SplPriorityQueue(); $pq->insert('a', 10); $pq->insert('b', 1); $pq->insert('c', 8); echo $pq->count() .PHP_EOL; //3 echo $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(); }