首页 > 其他 > 详细

leetcode 用栈实现队列 简单

时间:2021-09-01 15:03:57      阅读:16      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

用两个栈,分别为 stk1,stk2,当 push 的时候,直接 push 进 stk1,pop 时,如果 stk2 为空,则将 stk1 全部弹出并依次入栈 stk2,返回 stk2 的 top 即可。

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }

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

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int ret = peek();
        stk2.pop();
        return ret;
    }

    /** Get the front element. */
    int peek() {
        if(stk2.empty()) {
            while(!stk1.empty()) {
                stk2.push(stk1.top());
                stk1.pop();
            }
        }
        return stk2.top();
    }

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

private:
    stack<int> stk1, stk2;
};

 

leetcode 用栈实现队列 简单

原文:https://www.cnblogs.com/rookie-acmer/p/15208212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!