栈与队列|225.用队列实现栈

力扣题目链接

cpp 复制代码
class MyStack {
public:
    queue<int> que;
    /** Initialize your data structure here. */
    MyStack() {

    }
    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
    }
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = que.size();
        size--;
        while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
            que.push(que.front());
            que.pop();
        }
        int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
        que.pop();
        return result;
    }

    /** Get the top element. */
    int top() {
        return que.back();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.empty();
    }
};

这是c++优化后的解题,只用一个队列求解。

一、出错点

主要是代码实现部分容易出错,思路倒是清晰易懂。

pop()部分则是重点的理解思路

二、理解后的思路

一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。

代码随想录 (programmercarl.com)

三、总结

队列和栈的思路还是好理解的,

就是先进先出和先进后出

所以,我们重点要掌握的就是它的代码实现部分~

多敲代码咯!

相关推荐
catchadmin3 小时前
免费可商用 PHP 管理后台 CatchAdmin V5.4.1 发布,新增 MCP 支持
开发语言·php
jimy15 小时前
c++的 Type Traits (二、更详细版本)
开发语言·c++
碧海银沙音频科技研究院5 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
狗凯之家源码网5 小时前
纯 PHP+MySQL 应用市场系统源码实测!
开发语言·mysql·php
dishugj5 小时前
系统架构风险点、敏感点和权衡点的概念和区分
java·开发语言
通问AI5 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo6235 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y5 小时前
DAY2 滑动窗口
算法·leetcode·散列表
lvwangshu5 小时前
笛卡尔树
算法·图论
geovindu5 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模