php模拟栈

 1 <?php
 2 class phpStack{
 3     public $top = -1;
 4     public $size = 5;
 5     public $stack = array();
 6     
 7     public function __construct($size){
 8         $this->size = $size;
 9     }
10     
11     public function push($item){
12         if($this->isFull()){
13             return ;
14         }
15         $this->top++;
16         $this->stack[$this->top]=$item;
17     }
18     
19     public function pop(){
20         if($this->isEmpty()){
21             return ;
22         }
23         $ret = $this->stack[$this->top];
24         $this->top--;
25         return $ret;
26     }
27     
28     public function isFull(){
29         if(($this->top+1)>=$this->size){
30             echo "The stack is full!";
31             return true;
32         }
33     }
34     public function isEmpty(){
35         if($this->top==-1){
36             echo "The stack is empty";
37             return true;
38         }
39     }
40     public function show(){
41         for($i=$this->top;$i>-1;$i--){
42             echo $i."元素为:".$this->stack[$i]."<br/>";
43         }
44     }
45 }
46 ?>

测试代码:

<?php
require_once "stack.php";
header("Content-Type:text/html;charset=utf-8");
$stack = new phpStack(5);
$stack->push("1");
$stack->push("2");
$stack->push("1");
$stack->push("2");
$stack->push("1");
$stack->show();
?>

栈的用途:

子程序调用:在跳往子程序前,先将下一个指令的地址存促到栈中,直到子程序执行完成再就爱那个地址取出,回到原程序

处理递归:和子程序调用类似,只是出了存储下一个指令地址外,也将参数,区域变量等数据存入栈中。

表达式转换和求值://综合计算器

二叉树遍历://前序,中序,后序遍历

图形的深度优先(depth-first)搜索法://搜索算法

在php中array_push();array_pop();是系统实现入栈,出栈的方法。

posted @ 2013-07-16 23:50  simpman  阅读(237)  评论(0)    收藏  举报