利用php面向对象思想,栈的属性有top、最大存储数、和存储容器(这里利用了php数组)。
代码如下:实现了入栈、出栈、遍历栈的几个方法:
1 <?php 2 3 class Stack{ 4 const MAXSIZE = 4;// 栈最大容量 5 private $top = -1; 6 private $stack = array();// 利用数组存储数据 7 8 public function __construct(){ 9 $this->stack = array(); 10 } 11 12 // 入栈 13 public function push($ele){ 14 if ($this->top >= self::MAXSIZE-1){ 15 echo 'stack is full...'; 16 return false; 17 } 18 $this->stack[++$this->top] = $ele;// 此处必须是++i,先计算再使用 19 } 20 21 // 出栈,返回出栈元素 22 public function pop(){ 23 if ($this->top == -1){ 24 echo 'stack is empty...'; 25 return false; 26 } 27 $ele = $this->stack[$this->top]; 28 unset($this->stack[$this->top--]);// 此处必须是i--,先使用再计算(注意出栈和入栈的区别) 29 return $ele; 30 } 31 32 // 遍历栈 33 public function show(){ 34 if ($this->top == -1){ 35 echo 'stack is empty...'; 36 return false; 37 } 38 for($i=$this->top; $i>-1; $i--){ 39 echo $this->stack[$i].'<br/>'; 40 } 41 } 42 43 } 44 45 $stack = new Stack; 46 $stack->push(1); 47 $stack->push(2); 48 $stack->push(3); 49 $stack->push(4); 50 51 //print_r($stack); 52 $stack->show(); 53 54 55 $a = $stack->pop(); 56 $a = $stack->pop(); 57 $a = $stack->pop(); 58 59 $stack->show();