Welcome to our exploration of queues and deques. These structures frequently surface in everyday programming, managing everything from system processes to printer queues. In this lesson, our goal is to understand and implement queues
and deques
in PHP. Let's dive in!
A queue, similar to waiting in line at a store, operates on the "First In, First Out" or FIFO principle. PHP's SplQueue
class enables the implementation of queues. This class includes methods such as enqueue()
for adding items and dequeue()
for removing items.
php1<?php 2 3// Create a queue and add items 4$q = new SplQueue(); 5$q->enqueue("Apple"); 6$q->enqueue("Banana"); 7$q->enqueue("Cherry"); 8 9// Remove an item 10echo $q->dequeue() . "\n"; // Expects "Apple" 11 12?>
The dequeued item, "Apple"
, was the first item we inserted, demonstrating the FIFO principle of queues.
Before trying to remove items from our queue, let's ensure it is not empty. This precaution will prevent errors when attempting to dequeue from an empty queue.
php1<?php 2 3// Create a queue and enqueue items 4$q = new SplQueue(); 5$q->enqueue("Item 1"); 6$q->enqueue("Item 2"); 7 8// Check if the queue is non-empty, then dequeue an item 9if (!$q->isEmpty()) { 10 echo $q->dequeue() . "\n"; // Expects "Item 1" 11} 12 13?>
A deque, or "double-ended queue," allows the addition and removal of items from both ends. PHP provides the SplDoublyLinkedList
class for implementing deques. We can add items to both ends of our deque using the push()
method for the right end and the unshift()
method for the left. Similarly, we can remove elements from the left and right ends using shift()
and pop()
.
php1<?php 2 3// Create a deque and add items 4$d = new SplDoublyLinkedList(); 5$d->push("Middle"); 6$d->push("Right end"); 7$d->unshift("Left end"); 8 9// Remove an item 10echo $d->pop() . "\n"; // Expects "Right end" 11 12// Remove an item from the left 13echo $d->shift() . "\n"; // Expects "Left end" 14 15?>
Though PHP's SplDoublyLinkedList
doesn't have a built-in rotation method, we can implement rotation manually by repositioning elements in the list.
php1<?php 2 3// Create a deque 4$d = new SplDoublyLinkedList(); 5$d->push("Apple"); 6$d->push("Banana"); 7$d->push("Cherry"); 8 9// Rotate the deque to the right by 1 place 10$d->unshift($d->pop()); 11 12foreach ($d as $item) { 13 echo $item . PHP_EOL; // Expects [Cherry, Apple, Banana] in separate lines 14} 15 16?>
Here, the manual rotation shifts all items to the right by one position.
Congratulations on finishing this detailed study of queues and deques in PHP! You've learned their operating principles and how to construct and manipulate them using PHP's SPL classes.
Prospectively, we aim to comprehend additional data structures like these. This quest opens up a world of opportunities for expressing your ideas and solving complex problems. Are you ready for upcoming practice exercises to consolidate this new knowledge? Let's continue our exploration!