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: 2022/04/19 08:28 by 127.0.0.1

Access website using Tor Access website using i2p Wizardry and Steamworks PGP Key


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