用队列实现栈-力扣

本题是使用队列来实现栈,在栈实现队列时,我们使用了输入栈和输出栈来调整输出顺序,但时队列不同,队列元素先入先出,即使使用两个队列,也没法调整到先入后出。因此做法是依次将队列元素出队,然后再让其入队,当出队元素是 最初的队列 最后一个元素时,它就是栈顶元素。代码如下:

在top()函数中,可以直接返回 que.back(),也能直接得到队列的最后一个元素。

cpp 复制代码
class MyStack {
public:
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int size = que.size() - 1;
        while(size--){
            que.push(que.front());
            que.pop();
        }
        int result = que.front();
        que.pop();
        return result;
    }
    
    int top() {
        int result = this->pop();
        this->push(result);
        return result;
    }
    
    bool empty() {
        return que.empty();
    }
private:
    queue<int> que;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
相关推荐
BothSavage1 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn1 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽1 天前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
郝学胜_神的一滴1 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
先吃饱再说2 天前
判断回文字符串,从一行代码到双指针优化
算法
见过夏天2 天前
C++ 基础入门完全指南
c++
黄敬峰2 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构