php模拟顺序栈基本操作
一、总结
写函数什么永远记住边界情况:比如 echo "栈已满!<br/>" ; 栈已空这种,那就能多考虑几种情况,代码就很正宗了
1、对象生成和java一样,都是new关键字
2、 属性方法都是 -> 访问
3、对象的操作只是比java中少了变量类型而已,php不需要变量类型
二、代码
1 /** 2 * Class Stack 3 * 用PHP模拟顺序栈的基本操作 4 */ 5 class Stack{ 6 //用默认值直接初始化栈了,也可用构造方法初始化栈 7 private $top = -1; 8 private $maxSize = 5; 9 private $stack = array(); 10 11 //入栈 12 public function push($elem){ 13 if($this->top >= $this->maxSize-1){ 14 echo "栈已满!<br/>"; 15 return; 16 } 17 $this->top++; 18 $this->stack[$this->top] = $elem; 19 } 20 //出栈 21 public function pop(){ 22 if($this->top == -1){ 23 echo "栈是空的!"; 24 return ; 25 } 26 $elem = $this->stack[$this->top]; 27 unset($this->stack[$this->top]); 28 $this->top--; 29 return $elem; 30 } 31 //打印栈 32 public function show(){ 33 for($i=$this->top;$i>=0;$i--){ 34 echo $this->stack[$i]." "; 35 } 36 echo "<br/>"; 37 } 38 } 39 40 $stack = new Stack(); 41 $stack->push(3); 42 $stack->push(5); 43 $stack->push(8); 44 $stack->push(7); 45 $stack->push(9); 46 $stack->push(2); 47 $stack->show(); 48 $stack->pop(); 49 $stack->pop(); 50 $stack->pop(); 51 $stack->show();