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;
    }
}
posted @   鹿呦呦  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2018-03-22 ThinkPHP5.0源码学习之执行应用
点击右上角即可分享
微信分享提示
主题色彩