前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode|队1出栈+队2中转|225. 用两个队列实现栈

Leetcode|队1出栈+队2中转|225. 用两个队列实现栈

作者头像
SL_World
发布2022-01-10 15:11:56
2080
发布2022-01-10 15:11:56
举报
文章被收录于专栏:X

《225. 用两个队列实现栈》

《剑指 Offer 09. 用两个栈实现队列》

1 队1出栈+队2中转

  • 两个队列q1和q2,新入栈的元素先放入q2,然后将q1中元素逐个入队q2,再交换2队列即可
代码语言:javascript
复制
class MyStack {
public:
    queue<int> q1, q2;
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q2.push(x);
        while (!q1.empty()) {
            q2.push(q1.front());
            q1.pop();
        }
        swap(q1, q2);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res;
        if (q1.empty()) return -1;
        res = q1.front();
        q1.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        if (q1.empty()) return -1;
        return q1.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q1.empty();
    }
};

/**
 * 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();
 */
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/08/30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1 队1出栈+队2中转
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档