学习下队列,通过栈来实现队列

题来源力扣:https://leetcode-cn.com/probl...

思路:
  • 准备两个栈 inStack、outStack
  • 入队时,push 到 inStack 中
  • 出队时,

    • (1):如果 outStack是空的,将 inStack 所有的元素逐一弹出,push 到 outStack,outStack 弹出栈顶元素
    • (2):如果 outStack 不为空,outStack 弹出栈顶元素
php实现代码
<?php
/**
* 队列
* 使用栈实现队列
* https://leetcode-cn.com/problems/implement-queue-using-stacks/
* 1:准备两个栈 inStack、outStack
* 2: 入队时,push 到 inStack 中
* 3:出队时,
*      (1):如果 outStack是空的,将 inStack 所有的元素逐一弹出,push 到 outStack,outStack 弹出栈顶元素
*      (2):如果 outStack 不为空,outStack 弹出栈顶元素
*/

require '../stack/Stack.php';

class Queue
{
   protected $inStack;
   protected $outStack;

   public function __construct()
   {
       $this->inStack = new Stack();
       $this->outStack = new Stack();
   }

   /**
    * @param $item
    * push 一个元素
    * 入队
    */
   public function push($item)
   {
       $this->inStack->push($item);
   }

   /**
    * 弹出一个元素
    * 出队
    */
   public function pop()
   {
       $this->checkOutStack();
       return $this->outStack->pop();
   }

   /**
    * 获取队头元素
    */
   public function peek()
   {
       $this->checkOutStack();
       return $this->outStack->top();
   }



   /**
    * Returns whether the queue is empty.
    * @return Boolean
    */
   public function empty()
   {
       return $this->inStack->isEmpty() && $this->outStack->isEmpty();
   }

   private function checkOutStack(){
       if ($this->outStack->isEmpty()) {
           // 如果出队(outStack)的栈是空的, 将入队(inStack)的栈元素全部弹出并放到 出队的栈 outStack
           while (!$this->inStack->isEmpty()) {
               $this->outStack->push($this->inStack->pop());
           }
       }
   }
}

源代码下载:gitee


Theday
6 声望0 粉丝