php--数组来模拟堆栈

 1 <!DOCTYPE unspecified PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 2 <html>
 3 <head><title>php--数组来模拟堆栈</title></head>
 4 <body>
 5 <?php
 6  class MyStack{
 7      private $top=-1; //模拟栈底,指向-1
 8      private $maxSize=5; //模拟栈的容量为5
 9      private $stack=array();//用来数组来模拟,想数组内填入栈的内容
10       
11       //入栈操作
12      public function push($val){
13      ///先判断栈是否已满
14      if($this->top==$this->maxSize-1){
15      echo '栈满,不能添加</br>';
16      return; //栈满 返回
17      }
18      //先top上移,然后填充栈内容
19      $this->top++;
20      $this->stack[$this->top]=$val;
21      } 
22      //出栈
23      public function pop(){
24      if($this->top==-1){
25      echo '栈空</br>';
26      return; //空栈,无数据,返回
27      }
28      //取出栈顶的数据,同时把该数据返回,别忘了把top指针下移
29      $topValue=$this->stack[$this->top];
30      $this->top--;
31      return $topValue;
32 
33      }
34      //显示栈的所有信息
35      public function showStack(){
36      
37      if($this->top==-1){
38      echo '栈空!</br>';
39      return;//空栈,无数据,返回
40      }
41      //结合堆栈的数据结构,是后进先出类型的,因此从栈顶开始,依次往下读出栈的内容
42      for($i=$this->top;$i>-1;$i--){
43         echo 'Stack['.$i.']='.$this->stack[$i].'</br>'; 
44      }
45      }
46  }
47 
48 $stack=new MyStack();
49 $stack->push('111');
50 $stack->push('222');
51 $stack->showStack();
52 
53 
54 ?>
55 </body>
56 </html>

 

posted on 2013-03-15 23:24  以诺  阅读(254)  评论(0)    收藏  举报

导航