用队列实现栈-力扣

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

在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();
 */
相关推荐
利刃大大4 分钟前
【高并发内存池】五、页缓存的设计
c++·缓存·项目·内存池
C语言小火车37 分钟前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle1 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです1 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
Want5951 小时前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客2 小时前
c++ 杂记
开发语言·c++
jimmy.hua2 小时前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°2 小时前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx2 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
郝学胜-神的一滴3 小时前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生