資料結構之棧——鏈式儲存結構(php代碼實現)

來源:互聯網
上載者:User

標籤:資料結構 棧 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代碼實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.