implement-queue-by-two-stacks

使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。


class Queue {
public:
    stack<int> stack1;
    stack<int> stack2;

    Queue() {}

    void push(int element) {
        stack1.push(element);
    }
    
    int pop() {
        int tmp2=top();
        stack2.pop();
        return tmp2;
    }

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


你可能感兴趣的:(implement-queue-by-two-stacks)