首页 > 其他 > 详细

[剑指Offer]9-用两个栈实现队列

时间:2019-03-11 22:21:29      阅读:145      评论:0      收藏:0      [点我收藏+]

题目链接

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题意

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

解题思路

画图理解。

待做

用两个队列可实现栈。

代码

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

    int pop() {
        if (stack2.empty()) {
            while (!stack1.empty()) {
                int temp = stack1.top();
                stack1.pop();
                stack2.push(temp);
            }
        }
        if (stack2.empty()) {
            throw "the queue is empty!";
        }
        int  node = stack2.top();
        stack2.pop();
        return node;
    }

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

[剑指Offer]9-用两个栈实现队列

原文:https://www.cnblogs.com/coding-gaga/p/10513566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!