Skip to content

Instantly share code, notes, and snippets.

@matusstafura
Created January 12, 2023 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matusstafura/e70b13f3cbf38a3efc00b3dcb561bb59 to your computer and use it in GitHub Desktop.
Save matusstafura/e70b13f3cbf38a3efc00b3dcb561bb59 to your computer and use it in GitHub Desktop.
Basic operations in Queues in PHP
<?php
class Node
{
public $value;
public $next;
public function __construct($value)
{
$this->value = $value;
$this->next = null;
}
}
class Queue
{
public $first;
public $last;
public $length;
public function __construct(public $value)
{
$newNode = new Node($value);
$this->first = $newNode;
$this->last = $newNode;
$this->length = 1;
}
public function printQueue()
{
$temp = $this->first;
while ($temp != null) {
echo $temp->value."\n";
$temp = $temp->next;
}
}
public function enqueue($value)
{
$newNode = new Node($value);
if ($this->length == 0) {
$this->first = $newNode;
$this->last = $newNode;
} else {
$this->last->next = $newNode;
$this->last = $newNode;
}
$this->length++;
}
public function dequeue()
{
if ($this->length == 0) {
return null;
}
$temp = $this->first;
if ($this->length == 1) {
$this->first = null;
$this->last = null;
} else {
$this->first = $this->first->next;
$temp->next = null;
}
$this->length--;
return $temp;
}
}
$q = new Queue("first customer");
$q->enqueue("second customer");
$q->enqueue("third customer");
$q->dequeue();
$q->printQueue();
// ARRAYS:
// $queue = [];
// array_push($queue, 'youtube.com');
// array_push($queue, 'google.com');
// array_push($queue, 'gmail.com');
// array_shift($queue);
// $queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment