Stack Implementation

A short implementation of a stack in PHP.

Example usage:

<?php
 
$s = new Stack(array(3, 4, 5));
$s->push("6");
print $s->pop();
print $s->pop();
print $s->pop();
print $s->pop();

Code

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

fuss/php/data_structures/stacks.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.