1. 程式人生 > >3.1 棧的順序儲存結構

3.1 棧的順序儲存結構

<?php
header("content-type:text/html;charset=utf-8");
/**
 * 棧的順序儲存結構的基本操作
 *
 *包括
 * 1.順序棧的初始化 __contruct()
 * 2.銷燬棧 destroyStack()
 * 3.清空棧 clearStack()
 * 4.判斷棧是否為空 stackEmpty()
 * 5.獲取棧頂元素 getTop()
 * 6.進棧操作 push()
 * 7.出棧操作 pop()
 * 8.遍歷棧元素 traverse()
 */
class Linear_stack{
    const MAXSIZE = 20;
    
private $data; private $top; //初始化 public function __construct($data) { $this->data = $data; $this->top = count($data)-1; } //銷燬棧 public function destroyStack(){ $this->top = -1; $this->data = null; } //清空棧 public function
clearStack(){ $this->top = -1; $this->data = array(); } //判斷棧是否為空 public function stackEmpty(){ if($this->top == -1){ echo "棧為空"; }else{ echo "棧非空"; } } //獲取棧頂元素 public function getTop(){ if($this->top!=-1){
return $this->data[$this->top]; }else{ return false; } } //進棧操作:插入元素elem作為新的棧頂 public function push($elem){ if($this->top==self::MAXSIZE-1){ echo "棧已滿"; return false; }else{ $this->top++; $this->data[$this->top] = $elem; } } //出棧操作:刪除棧頂元素,並用value返回 public function pop(){ if($this->top==-1){ echo "棧已空"; return false; }else{ $value = $this->data[$this->top]; unset($this->data[$this->top]); $this->top--; return $value; } } //遍歷棧元素 public function traverse(){ $array = array(); for ($i = 0;$i<=$this->top;$i++){ array_push($array,$this->data[$i]); } return $array; } } ?>

下面來實現一下這些功能

<?php
header("content-type:text/html;charset=utf-8");
include 'linear_stack.class.php';
$data = array(1,2,3,4,5,6,7,8,9,10);
$stack = new Linear_stack($data);

echo "進棧元素666:";
echo "</br>";
$stack->push(666);
print_r($stack);
echo "</br>";
echo "</br>";

echo "棧頂元素出棧:";
echo "</br>";
$value = $stack->pop();
echo $value;
echo "</br>";

print_r($stack);
echo "</br>";
echo "</br>";

echo "遍歷棧:";
echo "</br>";
$array = $stack->traverse();
print_r($array);
echo "</br>";
echo "</br>";

echo "獲取棧頂元素:";
echo "</br>";
$top = $stack->getTop();
echo $top;
echo "</br>";
echo "</br>";

echo "判斷棧是否為空:";
echo "</br>";
$stack->stackEmpty();
echo "</br>";
echo "</br>";

echo "清空棧:";
echo "</br>";
$stack->clearStack();
print_r($stack);
echo "</br>";
echo "</br>";

echo "清空棧後,再次判斷棧是否為空:";
echo "</br>";
$stack->stackEmpty();
?>

最後的輸出結果是: