PHP算法每日一练 -- 堆栈
1 <?php 2 /**堆栈 使用数组模拟入栈和出栈*/ 3 class myStark{ 4 public $top = -1; 5 public $maxStark = 5; 6 public $stark = array(); 7 public function __construct(){ 8 9 } 10 /*入栈*/ 11 public function push($val){ 12 if($this->top > $this->maxStark - 1){ 13 return false; 14 } 15 $this->top ++; 16 $this->stark[$this->top] = $val; 17 } 18 /*出栈*/ 19 public function pop(){ 20 if($this->top <= -1){ 21 return false; 22 } 23 $return = $this->stark[$this->top]; 24 $this->top -- ; 25 return $return; 26 } 27 /*打印*/ 28 public function show(){ 29 for($i = $this->top;$i>-1;$i--){ 30 echo 'stack['.$i.']='.$this->stark[$i].'<br />'; 31 } 32 } 33 } 34 $stack = new myStark(); 35 $stack->push('香蕉'); 36 $stack->push('苹果'); 37 $stack->push('葡萄'); 38 $stack->push('梨子'); 39 $stack->push('草莓'); 40 $stack->show(); 41 $val = $stack->pop(); 42 echo $val.'出栈了!'. 43 $stack->show(); 44 ?>
源代码下载:Stark_1203.zip