用两个栈实现队列


  • 每次push,都push到stack1
  • 每次pop,如果stack2为空,就把stack1中的所有元素“倒入”stack2,这样就使得最先进入stack1的元素又回到了栈顶
class MyQueue {
public:
    stack<int> stack1;
    stack<int> stack2;

    MyQueue() {
        // do intialization if necessary
        stack1 = stack<int>();
        stack2 = stack<int>();
    }

    void push(int element) {
        // write your code here
        stack1.push(element);
    }

    int pop() {
        // write your code here
        int pop_elem = top();
        stack2.pop();
        return pop_elem;
    }

    int top() {
        // write your code here
        if (stack2.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        return stack2.top();
    }
};
优质内容筛选与推荐>>
1、北京大学Charls项目访员招募
2、iText 5.3.4 发布,Java 的 PDF 开发包
3、使用ArcEngine开发自定义Tool并发布为GP服务
4、Codeforces Round #278 (Div. 1) Strip RMQ
5、P3375 【模板】KMP字符串匹配


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号