Hello there! Today, we will unveil Queues in coding, likening them to a line in a coffee shop or a queue of print requests. Queues in computer science are First-In, First-Out (FIFO) structures. Consider this example: you're at a theme park — the first person in line for the roller coaster gets on first. Today's lesson revolves around this straightforward yet powerful concept. So, let's dive in!
Let's explore the implementation of Queues in PHP. An array
is ideal for implementing a Queue
. Let's define the Queue
:
php1class Queue { 2 private $queue; 3 private $size; 4 private $capacity; 5 6 public function __construct($capacity) { 7 $this->capacity = $capacity; 8 $this->queue = []; 9 $this->size = 0; 10 } 11 12 // Will return true if the Queue is full 13 public function isFull() { 14 return $this->size == $this->capacity; 15 } 16}
In the Queue
class above, the isFull()
method checks if our queue is already at maximum capacity.
Enqueue, a fancy term, denotes adding an item to the queue — the item lines up at the end. Here's how it plays out in our Queue
class:
php1public function enqueue($item) { 2 if ($this->isFull()) // Check if the queue is full 3 return; 4 5 array_push($this->queue, $item); // Add item at the end of the array 6 $this->size++; // Increment size 7}
The enqueue()
method checks if our queue has enough space before adding the item.
Just as enqueue
adds an element to our queue, dequeue
removes it. It extracts the element at the queue's beginning, reducing its size. However, we encounter an underflow condition if there are no elements to remove.
php1public function dequeue() { 2 if ($this->isEmpty()) // Check if the queue is empty 3 return null; 4 5 $this->size--; // Decrement size 6 return array_shift($this->queue); // Remove and return the first item 7} 8 9public function isEmpty() { 10 return $this->size == 0; 11}
The dequeue()
method checks for emptiness before dispatching the item.
The time complexity of the enqueue
operation is constant: O(1), as it only adds an item to the end of the queue. However, the dequeue
operation has a time complexity of O(n) because it removes the first element of the array, requiring a shift of all subsequent elements. The space complexity of both varies with the size of the queue, making it O(n).
We've learned about the Queue
, its operations, and its implementation in PHP. These techniques are fundamental for smooth functioning in daily life. They are invaluable and versatile in various applications, from data buffering in hardware to process scheduling in operating systems.
With your newfound knowledge of the Queue
data structure, it's time to level up! Coming next are some practice problems to enhance your understanding of these concepts. Let's dive in!