2stackToQueue

来源:互联网 发布:天气软件找不到列治文 编辑:程序博客网 时间:2024/06/06 20:24

2stackToQueue

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
[牛客url]https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

分析:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;
如果不为空,栈B直接出栈。

class Solution{public:    void push(int node) {       stack1.push(node);    }    int pop() {        if (stack2.empty()){            while (!stack1.empty()){                int temp = stack1.top();                stack2.push(temp);                stack1.pop();            }        }        if (stack2.empty()){            // 空的队列            //throw new exception("queue is empty");        }        int num = stack2.top();        stack2.pop();        return num;    }private:    stack<int> stack1;    stack<int> stack2;};
原创粉丝点击