首页 > 其他 > 详细

【剑指offer】用两个栈实现队列

时间:2018-12-27 02:29:48      阅读:139      评论:0      收藏:0      [点我收藏+]

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        int ans;
        //取出stack1栈底的元素:将Stack1中的元素全部出栈,暂时放在stack2中
        while (true) {
            ans = stack1.top();
            stack1.pop();
            if (stack1.empty()) {
                break;
            }
            stack2.push(ans);
        }
        //还原Stack1:将元素按入stack1的顺序再放回去,此时栈底元素已经取出
        while (!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return ans;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

 

【剑指offer】用两个栈实现队列

原文:https://www.cnblogs.com/lettleshel/p/10182750.html

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