/ Published in: PHP
Expand |
Embed | Plain Text
<?php /* * @class: Stack * @author: Michael Scribellito * @date: 7-5-11 */ require 'Node.php'; /* * Stack * ===== * * Represents a last-in-first-out (LIFO) stack of generic items. It supports * the usual push and pop operations, along with methods for peeking at the top * item, testing if the stack is empty, and iterating through the items in LIFO * order. * * All stack operations are constant time. */ class Stack { // size of the stack private $N; // top of stack private $first; // create an empty stack. public function __construct() { $this->N = 0; $this->first = NULL; } // is the stack empty? public function isEmpty() { return $this->first == NULL; } // return the number of items in the stack. public function size() { return $this->N; } // add the item to the stack. public function push($item) { // save a link to the list $oldfirst = $this->first; // create a new node for the beginning $this->first = new Node(); // set the instance variables in the new node $this->first->item = $item; $this->first->next = $oldfirst; // increment size $this->N++; } // return the item most recently added to the stack. // * throw an exception if the queue is empty. public function peek() { if ($this->isEmpty()) throw new Exception("Stack underflow"); return $this->first->item; } // delete and return the item most recently added to the stack. // * throw an exception if the queue is empty. public function pop() { if ($this->isEmpty()) throw new Exception("Stack underflow"); // save the most recently added item $item = $this->first->item; // remove the first node $this->first = $this->first->next; // decrement size $this->N--; return $item; } }
You need to login to post a comment.
