Leetcode基础刷题之PHP解析(225. Implement Stack using Queues)


2019-4-9 星期二  开始吧

上一题链接 Leetcode之PHP版题目解析(9. Palindrome Number)

4ab334814322f7d53168cd257cba0c90.png

题目描述

使用队列来实现栈操作。

题目分析

既然题目已经要求了,那么我们就不能直接简单粗暴的使用PHP的array_shift()和array_unshift().我这里定义了两个数组,来表示两个队列,然后利用一个辅助的变量就实现了利用队列来实现栈的操作。


具体实现1

 private $queue1=[];
     private $queue2=[];
  
    /**
     * Push element x onto stack.
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
        array_push($this->queue2,$x);
        while(!empty($this->queue1)){
            array_push($this->queue2,array_shift($this->queue1));
        }
        $temp=$this->queue1;
        $this->queue1=$this->queue2;
        $this->queue2=$temp;
    }
  
    /**
     * Removes the element on top of the stack and returns that element.
     * @return Integer
     */
    function pop() {
        return array_shift($this->queue1);
    }
  
    /**
     * Get the top element.
     * @return Integer
     */
    function top() {
        return current($this->queue1);
    }
  
    /**
     * Returns whether the stack is empty.
     * @return Boolean
     */
    function empty() {
        return empty($this->queue1)==true;
    }

Github整理地址:https://github.com/wuqinqiang/leetcode-php


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode PHP题解--D28 884. Uncommon Words from Two Sentences

>> 下一篇: Leetcode PHP题解--D29 973. K Closest Points to Origin