Queue Implementation

A short implementation of a queue in PHP.

Example usage:

<?php
 
$q = new Queue(array(3, 4, 5));
$q->enqueue("6");
print $q->dequeue();
print $q->dequeue();
print $q->dequeue();
print $q->dequeue();

Code

<?php
 
###########################################################################
##  Copyright (C) Wizardry and Steamworks 2016 - License: GNU GPLv3      ##
###########################################################################
class Queue
{
    protected $queue;
    protected $size;
 
    public function __construct($elements = array()) {
        switch(empty($elements)) {
            case TRUE:
                $this->queue = array();
                $this->size = 0;
                break;
            default:
                $this->queue = $elements;
                $this->size = count($elements);
                break;
        }
    }
 
    public function enqueue($element) {
        array_push($this->queue, $element);
        ++$this->size;
    }
 
    public function dequeue() {
        if ($this->isEmpty())
            throw new RunTimeException('Stack is empty!');
        --$this->size;
        return array_shift($this->queue);
    }
 
    public function peek() {
        return current($this->queue);
    }
 
    public function isEmpty() {
        return $this->size == 0;
    }
}

fuss/php/data_structures/queues.txt ยท Last modified: 2017/02/22 18:30 (external edit)

Access website using Tor Access website using i2p


For the copyright, license, warranty and privacy terms for the usage of this website please see the license, privacy and plagiarism pages.