標籤:else http ima val logs for null content 功能
今天開始進階自己的PHP,首先一切的程式設計語言都須要修鍊自己的“內功”,何為程式猿的“內功”,我想大概就是資料結構和演算法了吧 。畢竟是靈魂,是普通程式猿到進階程式猿的進階。
不多說。直接說主題——“棧”。
什麼是棧,所謂棧就是遵循“後進先出”的原則。
先進棧的最後出棧。
用PHP實現棧無需考慮棧溢出的情況,相對來說比較easy實現,例如以下是經過學習和參考後的代碼。
<?php
class Stack{
private $data=array();//定義棧
private $end=NULL;//定義棧指標。也成為棧頂。
//定義入棧操作
public function push($data){
if($this->end===NULL)
$this->end=0;
else
$this->end++;
$this->data[$this->end]=$data;
//php為弱類語言,不用考慮溢出情況
}
//出棧
public function pop(){
if(empty($this->data))
return false;
$ret=$this->data[$this->end];
array_splice($this->data,$this->end);//彈出後數組前移一位
$this->end--;
return $ret;
}
//取棧
public function get_stack(){
return $this->data;
}
}
?>
以上就是棧的基本操作,然後順便利用寫出來的棧實現了一個線上十進位轉換N工具。(N小於等於10.假設須要進行十進位以上的進位轉換須要添加功能)
<?php
class Stack{
private $data=array();//定義棧
private $end=NULL;//定義棧指標,也成為棧頂。
//定義入棧操作
public function push($data){
if($this->end===NULL)
$this->end=0;
else
$this->end++;
$this->data[$this->end]=$data;
//php為弱類語言,不用考慮溢出情況
}
//出棧
public function pop(){
if(empty($this->data))
return false;
$ret=$this->data[$this->end];
array_splice($this->data,$this->end);//彈出後數組前移一位
$this->end--;
return $ret;
}
//取棧
public function get_stack(){
return $this->data;
}
//定義進位轉換函式
public function transform($num,$to_num){
$result=NULL;//定義結果
while($num!=0){
$num_y=$num%$to_num;
$num=$num/$to_num;
$this->push($num_y);
if($num<$to_num){
$this->push(intval($num));
$num=0;
}
}
while(!empty($this->get_stack())){
echo $this->pop();
}
return true;
}
}
$a=new Stack;
$b=10;//須要轉換的十進位數
$c=5;//須要轉換的進位
$result=$a->transform($b,$c);
?>
下面為執行結果為20,測試成功。
小弟僅僅是淺談,假設哪裡不到位還希望請教。
淺談PHP資料結構之棧