PHP 数据结构队列(SplQueue)和优先队列(SplPriorityQueue)简单使用实例
这篇文章主要介绍了PHP 数据结构队列(SplQueue)和优先队列(SplPriorityQueue)简单使用实例,需要的朋友可以参考下
队列这种数据结构更简单,就像我们生活中排队一样,它的特性是先进先出(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简单使用:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$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(); } |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
