接着前面PHP数据结构来学习,今天写的是实现栈。
<?php
class stack //定义一个栈的类
{
private $size; //栈的空间大小
private $top; // 栈的指针
private $stack_arr; //栈的空间
public function __construct($size) //初始化一个空栈
{
$this->top=-1;
$this->size=$size;
$this->stack_arr=array();
}
public function push($data) //入栈操作,先判断栈是否已满
{
if($this->top==$this->size-1)
echo "The stack is full";
else
$this->stack_arr[++$this->top]=$data;
}
public function pop() //出栈,取栈顶元素,先判断是否为空栈
{
if($this->top==-1)
echo "The stack is empty";
else
return $this->stack_arr[$this->top--];
}
public function getlength() //获取栈的大小
{
return $this->top+1;
}
public function print_stack() //输出栈内元素
{
$tem=$this->top;
while($tem!=-1)
{
echo $this->stack_arr[$tem--];
}
}
}
$stack=new stack(3);
$stack->push('a');
$stack->push('b');
$stack->push('c');
echo $stack->getlength();
echo "<br/>";
$stack->print_stack();
echo "<br/>";
echo $stack->pop();
echo "<br/>";
$stack->push('d');
$stack->print_stack();
?>
运行结果截图如下: