Created
January 12, 2023 07:57
-
-
Save matusstafura/e70b13f3cbf38a3efc00b3dcb561bb59 to your computer and use it in GitHub Desktop.
Basic operations in Queues in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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