AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 应用
  • 更多
    • 题解
    • 分享
    • 商店
    • 问答
  • 吐槽
  • 登录/注册

AcWing 20. 用两个栈实现队列    原题链接    简单

作者: 作者的头像   米多奇香米饼 ,  2023-01-23 11:25:58 ,  所有人可见 ,  阅读 21


0


class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> stk, cache;
    MyQueue() {

    }

    /** Push element x to the back of queue. */
    void push(int x) {
        stk.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        //将stk中的元素倒着装到cache中
        while(stk.size()){
            cache.push(stk.top());
            stk.pop();
        }
        //取到cache中最上层的元素(stk中最底层的元素)
        int res=cache.top();
        //将此元素从栈中清除
        cache.pop();
        //将cache中的元素倒着装到stk中
        while(cache.size()){
            stk.push(cache.top());
            cache.pop();
        }
        return res;
    }

    /** Get the front element. */
    int peek() {
        //将stk中的元素倒着装到cache中
        while(stk.size()){
            cache.push(stk.top());
            stk.pop();
        }
        //取到cache中最上层的元素(stk中最底层的元素)
        int res=cache.top();
        //将cache中的元素倒着装到stk中
        while(cache.size()){
            stk.push(cache.top());
            cache.pop();
        }
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stk.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

0 评论

你确定删除吗?
1024
x

© 2018-2023 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息