用两个栈实现队列

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

https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

做法:

1)总是在stack1中push元素‘

2)当stack2不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以弹出;当stack2为空时,把stack1中的元素逐个弹出并压入stack2中。这时先进入的元素又处于stack2

的顶端,可以弹出。

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

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

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