首页 > 其他 > 详细

leetcode 232. Implement Queue using Stacks

时间:2016-03-18 21:40:52      阅读:198      评论:0      收藏:0      [点我收藏+]

经典题目,用两个栈实现队列

两个栈s[0]和s[1],一个用来入列,一个用来出列。

当s[1]为空时,执行pop()时就将s[0]的值push进s[1],再将s[1]的栈顶pop()

class Queue {
private:
    stack<int> s[2];
public:
    // Push element x to the back of queue.
    void push(int x) {
        s[0].push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if (s[1].empty())
        {
            while (!s[0].empty())
            {
                s[1].push(s[0].top());
                s[0].pop();
            }
        }
        s[1].pop();
    }

    // Get the front element.
    int peek(void) {
        if (s[1].empty())
        {
            while (!s[0].empty())
            {
                s[1].push(s[0].top());
                s[0].pop();
            }
        }
        return s[1].top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return (s[0].empty() && s[1].empty());
    }
};

 

leetcode 232. Implement Queue using Stacks

原文:http://www.cnblogs.com/tonychen-tobeTopCoder/p/5293436.html

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