用两个栈实现队列

来源:互联网 发布:按键精灵免费网络验证 编辑:程序博客网 时间:2024/05/01 18:59

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


分析:栈是先进后出结构,队列是先进先出结构,但是这里有两个栈,因此,Push操作时,我假设用stack1来存储,出栈时即Pop操作,将stack1的元素出栈然后入栈stack2,然后再stack2出栈,但是出栈时要考虑stack2是否为空,如果为空则执行之前的Pop操作,如果不为空,那么就不用stack1的元素入栈stack2了,直接,stack2出栈完成Pop操作


思路:入栈(队列Push操作时)直接存入stack1,出栈(队列Pop操作时),先判断stack2是否为空,如果不为空则直接stack2出栈完成Pop操作,否则,将stack1的元素出栈然后入栈stack2,然后再stack2出栈,可能有些情况没考虑全,之后再做补充


C++代码:

class Solution{public:    void push(int node) {        stack1.push(node);    }    int pop() {        int node2;        if(!stack2.empty()){            node2 = stack2.top();            stack2.pop();            return node2;        }        while(!stack1.empty()){            int node1 = stack1.top();            stack1.pop();            stack2.push(node1);        }        node2 = stack2.top();        stack2.pop();        return node2;    }private:    stack<int> stack1;    stack<int> stack2;};


0 0