Simple usage examples of PHP data structure queue (SplQueue) and priority queue (SplPriorityQueue), priority queue data structure_PHP tutorial

WBOY
Release: 2016-07-13 09:54:02
Original
1090 people have browsed it

PHP data structure queue (SplQueue) and priority queue (SplPriorityQueue) simple usage examples, priority queue data structure

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();
}
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998573.htmlTechArticlePHP data structure queue (SplQueue) and priority queue (SplPriorityQueue) simple usage examples, priority queue data structure queue such The data structure is simpler, just like queuing in our lives,...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template