用栈实现队列

class MyQueue {
public:
    stack<int>stIn;
    stack<int>stOut;
    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    // 从队列开头移除并返回元素
    int pop() {
        if(stOut.empty())   // 当stOut为空时,再从StIn中导入数据(导入stIn中的所有数据)
        {
            while(!stIn.empty())
            {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }
    
    // 返回队列的第一个元素
    int peek() {
        int res = this->pop();
        stOut.push(res);
        return res;
    }
    
    // 返回队列是否为空
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
posted @   香花草的味道  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示