用两个栈实现队列

来源:互联网 发布:淘宝纠纷报警有用吗 编辑:程序博客网 时间:2024/06/05 19:46

用两个栈实现队列

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


解题思路:

1.stack1作为存储栈。

2.stack2作为临时交换栈

3.实现入栈时,新元素直接通过push函数存储在stack1

4.实现出栈时,把stack1中的n-1个元素依次利用pop和push倒入stack2,再把stack1中的最后一个元素出栈,最后把stack2的元素全部倒入stack1。


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


0 0
原创粉丝点击