题解 | #用两个栈实现队列#

用两个栈实现队列

http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

使用stack1作为压入栈,使用stack2作为弹出栈;

压入时直接压入stack1,弹出时判断stack2是否为空,如果为空,证明队列头元素在stack1的底部,则依次将stack1中的元素压入stack2中;如果不为空,证明对头元素仍然在stack2的上层,直接弹出stack2中元素即可

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

    int pop() {
        if(stack2.empty()) {
            while(stack1.size()) {
                int x = stack1.top();
                stack1.pop();
                stack2.push(x);
            }
        }
        int res = stack2.top();
        stack2.pop();
        return res;
    }

private:
    stack<int> stack1; // 压入栈
    stack<int> stack2; // 弹出栈
};
全部评论

相关推荐

点赞 评论 收藏
分享
给我发了笔试链接,想着等晚上回去做,结果还没做流程就终止了
伟大的小黄鸭在学习:我猜就是笔试几乎没用,就是用来给用人部门拖时间复筛简历的,可能用人部门筛到你简历觉得不合适就提前挂了
投递小鹏汽车等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务