標籤:資料結構 棧 php
<?php/** 1. DestroyStack(): 棧的銷毀 2. ClearStack(): 將棧置為空白棧 3. StackEmpty(): 判斷棧是否為空白 4. StackLength(): 返回棧的長度 5. GetTop(): 取得棧頂的元素 6. Push(): 插入新的棧頂元素 7. Pop(): 刪除棧頂元素 8. StackTraverse(): 遍曆棧元素 */class LNode{ public $data; public $next; public function __construct($data=null){ $this->data=$data; $this->next=null; }}class LinkStack{ private $top;//用於指向棧頂結點,也就是第一個結點。它相當於頭指標。 private $length;//用於指定鏈棧的長度 public function __construct(){ $this->top=null; $this->length=0; } //銷毀鏈棧 public function DestroyStack(){ while($this->top){ $p=$this->top->next; unset($this->top); $this->top=$p; } $this->length=0; } //清空鏈棧 public function ClearStack(){ $p=$this->top; while($p){ $q=$p->next; unset($p); $p=$q; } $this->top=null; $this->length=0; } //鏈棧是否為空白 public function StackEmpty(){ if($this->top==null){ return ‘Null‘; }else{ return ‘NO Null‘; } } //鏈棧的長度 public function StackLength(){ return $this->length; } //取得棧頂的元素 public function GetTop(){ if($this->top!=null){ return $this->top->data; } } //插入新的棧頂結點 public function Push(){ $node=new LNode(mt_rand(10,20)); $node->next=$this->top; $this->top=$node; $this->length++; } //刪除棧頂元素 public function Pop(){ if($this->top!=null){ $p=$this->top->next; unset($this->top); $this->top=$p; $this->length--; } } //遍曆棧元素 public function StackTraverse(){ $arr=array(); if($this->top !=null){ $p=$this->top; while($p){ $arr[]=$p->data; $p=$p->next; } } return $arr; }}
本文出自 “一切皆有可能” 部落格,請務必保留此出處http://noican.blog.51cto.com/4081966/1599911
資料結構之棧——鏈式儲存結構(php代碼實現)