算法与数据结构题目的 PHP 实现:栈和队列 由两个栈组成的队列
生活随笔
收集整理的這篇文章主要介紹了
算法与数据结构题目的 PHP 实现:栈和队列 由两个栈组成的队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:同樣使用 PHP 的數組模擬棧。棧的特點是先進后出,隊列的特點是先進先出,可以用第一個棧(StackPush)作為壓入棧,壓入數據的時候只往這個棧中壓入數據,第二個棧作(StackPop)為彈出棧,在彈出數據的時候只從這個棧中彈出。在彈出之前,把壓入棧的數據全部 彈出至 彈出棧,再把彈出棧的數據彈出。
代碼:
1 <?php 2 3 class TwoStacksQueue { 4 //壓入棧 5 private $StackPush = array(); 6 //彈出棧 7 private $StackPop = array(); 8 9 //壓入棧 壓入數據 10 public function add($pushInt) { 11 array_push($this->StackPush, $pushInt); 12 } 13 14 //將數據從壓入棧 倒入 彈出棧 15 public function poll() { 16 if (empty($this->StackPush) && empty($this->StackPop)) { 17 echo 'Queue is empty.'; 18 exit(); 19 } else if (empty($this->StackPop)) { 20 while (!empty($this->StackPush)) { 21 $pop = array_pop($this->StackPush); 22 array_push($this->StackPop, $pop); 23 } 24 } 25 } 26 27 //查看彈出棧的棧頂元素 28 public function peek() { 29 if (empty($this->StackPush) && empty($this->StackPop)) { 30 echo 'Queue is empty.'; 31 exit(); 32 } else if (empty($this->StackPop)) { 33 while (!empty($this->StackPush)) { 34 $pop = array_pop($this->StackPush); 35 array_push($this->StackPop, $pop); 36 } 37 } 38 $count = count($this->StackPop); 39 return $this->StackPop[$count - 1]; 40 } 41 42 //查看壓入棧 43 public function getStackPush() { 44 return $this->StackPush; 45 } 46 47 //查看彈出棧 48 public function getStackPop() { 49 return $this->StackPop; 50 } 51 } 52 53 $queue = new TwoStacksQueue(); 54 $queue->add(1); 55 $queue->add(2); 56 $queue->add(3); 57 $queue->add(4); 58 $queue->add(5); 59 var_dump($queue->getStackPush()); 60 $queue->poll(); 61 var_dump($queue->getStackPush()); 62 var_dump($queue->getStackPop()); 63 var_dump($queue->peek());輸出:
array0 => int 11 => int 22 => int 33 => int 44 => int 5 arrayempty array0 => int 51 => int 42 => int 33 => int 24 => int 1 int 1?
轉載于:https://www.cnblogs.com/dee0912/p/4912124.html
總結
以上是生活随笔為你收集整理的算法与数据结构题目的 PHP 实现:栈和队列 由两个栈组成的队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用window.navigator.u
- 下一篇: Google Protocol Buff