標籤:資料結構 棧 php
<?php/** 1. DestroyStack(): 棧的銷毀 2. ClearStack(): 將棧置為空白棧 3. StackEmpty(): 判斷棧是否為空白 4. StackLength(): 返回棧的長度 5. GetTop(): 取得棧頂的元素 6. Push(): 插入新的棧頂元素 7. Pop(): 刪除棧頂元素 8. StackTraverse(): 遍曆棧元素 *///除了push和pop方法外,其餘的方法和之前線性表的順序儲存的代碼實現基本相同class SqStack{ public $SqArr;//此處是用於儲存棧元素的數組 private $top; //表示棧頂,相當於數組的最後一個元素下標 public function __construct($SqArr){ $this->SqArr=$SqArr; $this->top=count($SqArr)-1; } //棧的銷毀 public function DestroyStack(){ $this->SqArr=null; $this->top=-1; } //將棧置為空白棧 public function ClearStack(){ $this->SqArr=array(); $this->top=-1; } //判斷棧是否為空白 public function StackEmpty(){ if($this->top==-1){ return ‘Null‘; }else{ return ‘No Null‘; } } //返回棧的長度 public function StackLength(){ if(is_null($this->SqArr)){ return null; } return $this->top+1; } //取得棧頂的元素 public function GetTop(){ if($this->top==-1){ return ‘ERROR‘; } return $this->SqArr[$this->top]; } //插入新的棧頂元素 public function Push($elem){ $this->top++; $this->SqArr[$this->top]=$elem; } //刪除棧頂元素 public function Pop(){ if($this->top==-1){ return ‘ERROR‘; } $p=$this->SqArr[$this->top]; unset($this->SqArr[$this->top]); //注,此句可以有也可以沒有,如果此語句存在,則在堆棧記憶體中會將此棧頂元素真正的刪除;倘若沒有此語句,則僅僅是top指標不在指向此棧頂元素了。另外,此語句有沒有對應的下面的遍曆方法的實現也不同,沒有則對應StackTraverse()方法,有則對應StackTraverse2()方法。 $this->top--; return $p; } //遍曆棧元素 public function StackTraverse(){ if(is_null($this->SqArr)){ return null; } $arr=array(); for($i=0;$i<=$this->top;$i++){ $arr[]=$this->SqArr[$i]; } return $arr; } public function StackTraverse2(){ return $this->SqArr; }}
本文出自 “一切皆有可能” 部落格,請務必保留此出處http://noican.blog.51cto.com/4081966/1599657
資料結構之棧——順序儲存結構(php代碼實現)