Implement a priority queue using SplPriorityQueue
PHP already has a built-in support for implementing a priority queue using SPL. We can use the SplPriorityQueue
class to implement our priority queues. Here is the sample previous example using a linked list, but this time we are choosing SPL:
class MyPQ extends SplPriorityQueue { public function compare($priority1, $priority2) { return $priority1 <=> $priority2; } } $agents = new MyPQ(); $agents->insert("Fred", 1); $agents->insert("John", 2); $agents->insert("Keith", 3); $agents->insert("Adiyan", 4); $agents->insert("Mikhael", 2); //mode of extraction $agents->setExtractFlags(MyPQ::EXTR_BOTH); //Go to TOP $agents->top(); while ($agents->valid()) { $current = $agents->current(); echo $current['data'] . "\n"; $agents->next(); }
This will produce the same result as the linked list example. The added advantage of extending to our own MyPQ
class is that we can define whether...