浅谈PHP数据结构之栈

今天開始进阶自己的PHP,首先一切的编程语言都须要修炼自己的“内功”,何为程序猿的“内功”,我想大概就是数据结构和算法了吧 。毕竟是灵魂,是普通程序猿到高级程序猿的进阶。

http://pic002.cnblogs.com/images/2012/152332/2012060200472563.png

不多说。直接说主题——“栈”。

什么是栈,所谓栈就是遵循“后进先出”的原则。

http://pic002.cnblogs.com/images/2012/152332/2012060111254129.jpg

先进栈的最后出栈。

用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,測试成功。
小弟仅仅是浅谈,假设哪里不到位还希望请教。



posted @ 2017-08-06 17:41  clnchanpin  阅读(191)  评论(0编辑  收藏  举报