5 用两个栈实现队列

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

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

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

入队:将元素进栈A
出队:首先判断栈B是否为空,若栈B为空,将栈A中的元素全部压入栈B(若栈A中没有元素,直接返回),再pop出栈B的栈顶元素,若栈B非空,直接pop出栈B的栈顶元素。

猜你喜欢

转载自blog.csdn.net/PartyPartyAnimal/article/details/79628721