Advertisement
misael_arc

Stack

Oct 15th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.95 KB | None | 0 0
  1. <?php
  2. class Stack {
  3.     protected $stack;
  4.     protected $limit;
  5.  
  6.     public function __construct($limit = 10, $initial = array()) {
  7.         $this->stack = $initial;
  8.         $this->limit = $limit;
  9.     }
  10.  
  11.     public function push($item) {
  12.         if (count($this->stack) < $this->limit) {
  13.             array_unshift($this->stack, $item);
  14.         } else {
  15.             throw new RunTimeException('Stack is full!');
  16.         }
  17.     }
  18.  
  19.     public function pop() {
  20.         if ($this->isEmpty()) {
  21.             throw new RunTimeException('Stack is empty!');
  22.         } else {
  23.             return array_shift($this->stack);
  24.         }
  25.     }
  26.  
  27.     public function top() {
  28.         return current($this->stack);
  29.     }
  30.     public function isEmpty() {
  31.         return empty($this->stack);
  32.     }
  33.  
  34. }
  35.  
  36. $stack = new Stack();
  37. $stack->push(1);
  38. $stack->push(2);
  39. $stack->push(3);
  40. $stack->push(4);
  41. $stack->push(5);
  42.  
  43. $stack = new Stack(10, array(1, 2, 3, 4, 5));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement