LeetCode || Implement Stack using Queues

来源:互联网 发布:微信一键转发软件苹果 编辑:程序博客网 时间:2024/05/16 06:54
class Stack {public:    // Push element x onto stack.    void push(int x) {        q1.push(x);    }    // Removes the element on top of the stack.    void pop() {        if(q1.size() == 0)        {            while(q2.size() > 1)            {                q1.push(q2.front());                q2.pop();            }                        q2.pop();        }        else        {            while(q1.size() > 1)            {                q2.push(q1.front());                q1.pop();            }                        q1.pop();        }    }    // Get the top element.    int top() {        if(q1.size() == 0)        {            while(q2.size() > 1)            {                q1.push(q2.front());                q2.pop();            }                        int top = q2.front();            q1.push(top);            q2.pop();            return top;        }        else        {            while(q1.size() > 1)            {                q2.push(q1.front());                q1.pop();            }            int top = q1.front();            q2.push(top);            q1.pop();            return top;        }    }    // Return whether the stack is empty.    bool empty() {        if(q1.size() == 0 && q2.size() == 0)            return true;        return false;    }        queue<int> q1;    queue<int> q2;};

0 0
原创粉丝点击