码迷,mamicode.com
首页 > 其他好文 > 详细

Implement Queue using Stacks

时间:2015-07-07 16:29:08      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        while (!s2.empty())
        {
            int val = s2.top();
            s1.push(val);
            s2.pop();
        }
        s1.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        while (!s1.empty())
        {
            int val = s1.top();
            s2.push(val);
            s1.pop();
        }
        if (!s2.empty())
            s2.pop();
    }

    // Get the front element.
    int peek(void) {
        while (!s1.empty())
        {
            int val = s1.top();
            s2.push(val);
            s1.pop();
        }
        return s2.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        if (s1.empty() && s2.empty())
            return true;
        else
            return false;
    }

private:
    stack<int> s1;
    stack<int> s2;
};

 

Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/acode/p/4627134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!