用队列实现栈

 

 

复制代码
/*
 * @lc app=leetcode.cn id=225 lang=cpp
 *
 * [225] 用队列实现栈
 */

// @lc code=start
class MyStack
{
public:
    MyStack()
    {
        q1 = new queue<int>;
        q2 = new queue<int>;
    }
    ~MyStack()
    {
        delete q1;
        delete q2;
        q1 = nullptr;
        q2 = nullptr;
    }
    void push(int x)
    {
        q1->push(x);
        while (!q2->empty())
        {
            q1->push(q2->front());
            q2->pop();
        }
        queue<int> *p = q1;
        q1 = q2;
        q2 = p;
    }

    int pop()
    {
        int val = q2->front();
        q2->pop();
        return val;
    }

    int top()
    {
        return q2->front();
    }

    bool empty()
    {
        return q2->empty();
    }

private:
    queue<int> *q1;
    queue<int> *q2;
};

/**
 * 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();
 */
// @lc code=end
复制代码

 

posted @   AngDH  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示