栈与队列|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)

三、总结

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

就是先进先出和先进后出

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

多敲代码咯!

相关推荐
码农小韩4 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
木风小助理5 分钟前
`mapfile`命令详解:Bash中高效的文本至数组转换工具
开发语言·chrome·bash
mit6.82410 分钟前
几何|阻碍链
算法
有一个好名字12 分钟前
力扣-小行星碰撞
算法·leetcode·职场和发展
MM_MS12 分钟前
Halcon图像锐化和图像增强、窗口的相关算子
大数据·图像处理·人工智能·opencv·算法·计算机视觉·视觉检测
yyy(十一月限定版)14 分钟前
初始matlab
开发语言·matlab
LawrenceLan15 分钟前
Flutter 零基础入门(九):构造函数、命名构造函数与 this 关键字
开发语言·flutter·dart
listhi52015 分钟前
基于MATLAB的支持向量机(SVM)医学图像分割方法
开发语言·matlab
lamentropetion20 分钟前
E - Equal Tree Sums CF1656E
算法
hui函数21 分钟前
如何解决 pip install 编译报错 g++: command not found(缺少 C++ 编译器)问题
开发语言·c++·pip