Last active
August 23, 2016 10:27
-
-
Save antoniopicone/a67f8e06158ee9952ad8a42da71bf583 to your computer and use it in GitHub Desktop.
A simple PHP implementation of a Queue
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 $data; | |
public $next; | |
public function __construct($data) | |
{ | |
$this->data = $data; | |
$this->next = NULL; | |
} | |
public function getData() { | |
return $this->data; | |
} | |
} | |
class Queue { | |
private $head; | |
private $tail; | |
public function __construct() | |
{ | |
$this->head = $this->tail = NULL; | |
} | |
public function enqueue($data) { | |
$new = new Node($data); | |
if($this->tail == NULL) { | |
$this->head = &$new; | |
} | |
else { | |
$this->tail->next = &$new; | |
} | |
$this->tail = &$new; | |
} | |
public function isEmpty() { | |
return $this->tail == NULL; | |
} | |
public function dequeue() { | |
if($this->isEmpty()) throw new Exception("The queue is empty"); | |
$head = $this->head; | |
$this->head = $this->head->next; | |
return $head->getData(); | |
} | |
public function listQueue() { | |
$current = $this->head; | |
while ($current != NULL) { | |
echo $current->getData()."->"; | |
$current = $current->next; | |
} | |
echo "NULL\n"; | |
} | |
} | |
$q = new Queue(); | |
$q->enqueue(3); | |
$q->enqueue(9); | |
$q->listQueue(); | |
$q->enqueue(2); | |
$q->listQueue(); | |
echo 'de-queueing '.$q->dequeue()."\n"; | |
$q->listQueue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment