本文實(shí)例講述了PHP實(shí)現(xiàn)的棧數(shù)據(jù)結(jié)構(gòu)。分享給大家供大家參考,具體如下:
利用php面向?qū)ο笏枷耄瑮5膶傩杂衪op、最大存儲(chǔ)數(shù)、和存儲(chǔ)容器(這里利用了php數(shù)組)。
代碼如下:實(shí)現(xiàn)了入棧、出棧、遍歷棧的幾個(gè)方法:
<?php class Stack{ const MAXSIZE = 4;// 棧最大容量 private $top = -1; private $stack = array();// 利用數(shù)組存儲(chǔ)數(shù)據(jù) public function __construct(){ $this->stack = array(); } // 入棧 public function push($ele){ if ($this->top >= self::MAXSIZE-1){ echo 'stack is full...'; return false; } $this->stack[++$this->top] = $ele;// 此處必須是++i,先計(jì)算再使用 } // 出棧,返回出棧元素 public function pop(){ if ($this->top == -1){ echo 'stack is empty...'; return false; } $ele = $this->stack[$this->top]; unset($this->stack[$this->top--]);// 此處必須是i--,先使用再計(jì)算(注意出棧和入棧的區(qū)別) return $ele; } // 遍歷棧 public function show(){ if ($this->top == -1){ echo 'stack is empty...'; return false; } for($i=$this->top; $i>-1; $i--){ echo $this->stack[$i].'<br/>'; } } } $stack = new Stack; $stack->push(1); $stack->push(2); $stack->push(3); $stack->push(4); //print_r($stack); $stack->show(); $a = $stack->pop(); $a = $stack->pop(); $a = $stack->pop(); $stack->show();
運(yùn)行結(jié)果:
4 3 2 1 1
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP常用遍歷算法與技巧總結(jié)》及《PHP數(shù)學(xué)運(yùn)算技巧總結(jié)》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:
- PHP基于數(shù)組實(shí)現(xiàn)的堆棧和隊(duì)列功能示例
- 關(guān)于PHP堆棧與列隊(duì)的學(xué)習(xí)
- php線性表的入棧與出棧實(shí)例分析
- PHP基于堆棧實(shí)現(xiàn)的高級(jí)計(jì)算器功能示例
- PHP實(shí)現(xiàn)基于棧的后綴表達(dá)式求值功能
- PHP使用數(shù)組實(shí)現(xiàn)隊(duì)列
- php實(shí)現(xiàn)的雙向隊(duì)列類實(shí)例
- 隊(duì)列在編程中的實(shí)際應(yīng)用(php)
- php基于雙向循環(huán)隊(duì)列實(shí)現(xiàn)歷史記錄的前進(jìn)后退等功能
- PHP實(shí)現(xiàn)的鏈?zhǔn)疥?duì)列結(jié)構(gòu)示例
- PHP使用兩個(gè)棧實(shí)現(xiàn)隊(duì)列功能的方法
【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。