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

题目链接:用两个栈实现队列

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

题解:

stack2为空时,用stack1入栈,stack2出栈就是队列的顺序。当stack2不为空时,stack1继续插入的话,就直接先输出2再操作。

 

代码: 

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

    int pop() {
        if(stack2.empty()){
            while(stack1.size()>0){
                int data = stack1.top();
                stack1.pop();
                stack2.push(data);
            }
        }
        int ans = stack2.top();
        stack2.pop();
        return ans;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
原文地址:https://www.cnblogs.com/Asumi/p/12398548.html