LeetCode#225-Implement Stack using Queues-用队列实现栈

一、题目

使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

注意:

  • 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

题解

我们都知道,栈是“先进后出”的数据结构,栈内元素从顶端压入(push),从顶端弹出(pop)。队列与栈相反,是“先进先出”的数据结构,队列中元素只能从后端(rear)入队(push),然后从前端(front)端出队(pop)。

  • 解法1:两个队列

这里用的是数组表示队列,空间复杂度O(n),时间复杂度分push 和 pop ,前者是O(1),后者是O(n)。

class MyStack {
    /**
     * Initialize your data structure here.
     */
    function __construct() {
        $this->q1 = [];
        $this->q2 = [];
    }

    /**
     * Push element x onto stack.
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
        $this->q1[] = $x;
    }

    /**
     * Removes the element on top of the stack and returns that element.
     * @return Integer
     */
    function pop() {
        while(count($this->q1) > 1) {
            $this->q2[] = array_shift($this->q1);
        }
        $top = array_shift($this->q1);
        $this->q1 = $this->q2;
        $this->q2 = [];
        return $top;
    }

    /**
     * Get the top element.
     * @return Integer
     */
    function top() {
        return end($this->q1);
    }

    /**
     * Returns whether the stack is empty.
     * @return Boolean
     */
    function empty() {
        return empty($this->q1) ? true : false;
    }
}
  • 解法2:单队列

用一个队列,将新元素压入队尾,然后将队首元素弹出,放到新元素后面,直到新元素在队首为止,此时队首元素就是栈顶元素。
空间复杂度O(n),时间复杂度分push 和 pop ,前者是O(n),后者是O(1)。

class MyStack {
    /**
     * Initialize your data structure here.
     */
    function __construct() {
        $this->q = [];
    }

    /**
     * Push element x onto stack.
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
        $this->q[] = $x;
        $len = count($this->q);
        while ($len > 1) {
            $this->q[] = array_shift($this->q);
            $len--;
        }
    }

    /**
     * Removes the element on top of the stack and returns that element.
     * @return Integer
     */
    function pop() {
        return array_shift($this->q);
    }

    /**
     * Get the top element.
     * @return Integer
     */
    function top() {
        return $this->q[0];
    }

    /**
     * Returns whether the stack is empty.
     * @return Boolean
     */
    function empty() {
        return empty($this->q) ? true : false;
    }
}
原文地址:https://www.cnblogs.com/sunshineliulu/p/12547737.html