1. 程式人生 > >3.3 棧的鏈式儲存結構

3.3 棧的鏈式儲存結構

<?php
header("content-type:text/html;charset=utf-8");
/**
 * 棧的鏈式儲存結構的基本操作
 *
 *包括
 * 1.初始化 __contruct()
 * 2.進棧操作 push()
 * 3.出棧操作 pop()
 * 4.銷燬棧 destroyStack()
 * 5.清空棧 clearStack()
 * 6.遍歷棧 stackTraverse()
 */
class Node{
    public $data;
    public $next;
    public function __construct($data=null
) { $this->data = $data; $this->next = null; } } class Node_stack{ private $top; private $count; //初始化棧 public function __construct(){ $this->top=null; $this->count=0; } //進棧操作push() public function push($elem){ $node
= new Node(); $node->data = $elem; $node->next = $this->top; $this->top = $node; $this->count++; } //出棧操作pop() public function pop(){ if($this->top == null){ echo "棧已空"; return false; }else{
$value = $this->top->data; unset($this->top->data); $this->top = $this->top->next; $this->count--; return $value; } } //銷燬棧 public function destroyStack(){ $p=$this->top; while ($p){ $p=$this->top->next; unset($this->top); $this->top=$p; } $this->count=0; } //清空棧 public function clearStack(){ $p=$this->top; while ($p){ $p->next = null; } $this->top=null; $this->count=0; } //遍歷棧 public function stackTraverse(){ if($this->top ==null){ echo "棧已空"; return false; }else{ $array = array(); $p=$this->top; while ($p){ array_push($array,$p->data); $p = $p->next; } return $array; } } } ?>

實現函式:

<?php
header("content-type:text/html;charset=utf-8");
include 'node_stack.class.php';
$node_stack = new Node_stack();
echo "進棧操作:";
echo "</br>";
$node_stack->push(1);
$node_stack->push(2);
$node_stack->push(3);
$node_stack->push(4);
$node_stack->push(5);
print_r($node_stack);
echo "</br>";
echo "</br>";
echo "遍歷棧:";
echo "</br>";
$stack_array = $node_stack->stackTraverse();
print_r($stack_array);
echo "</br>";
echo "</br>";
echo "出棧操作:";
echo "</br>";
$value = $node_stack->pop();
echo $value;
echo "</br>";
print_r($node_stack);
echo "</br>";
echo "直至棧空:";
echo "</br>";
$node_stack->pop();
$node_stack->pop();
$node_stack->pop();
$node_stack->pop();
$node_stack->pop();
echo "</br>";
print_r($node_stack);
echo "</br>";
echo "</br>";

?>

實現結果: