思路:同样使用 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());
输出:
array 0 => int 1 1 => int 2 2 => int 3 3 => int 4 4 => int 5 array empty array 0 => int 5 1 => int 4 2 => int 3 3 => int 2 4 => int 1 int 1