关于php:PHP使用栈实现队列

8次阅读

共计 1196 个字符,预计需要花费 3 分钟才能阅读完成。

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

题起源力扣: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

正文完
 0