225. Implement Stack using Queues

来源:互联网 发布:c语言char怎么输出 编辑:程序博客网 时间:2024/06/05 11:31

这里写图片描述
这里写图片描述

    MyStack() {    }    /** Push element x onto stack. */    void push(int x) {        q2.push(x);        while(q2.size()>1){            q1.push(q2.front());            q2.pop();        }    }    /** Removes the element on top of the stack and returns that element. */    int pop() {       top();        int x=q2.front();        q2.pop();        return x;    }    /** Get the top element. */    int top() {        if(q2.empty()){            for(int i=0;i<(int)q1.size()-1;i++){                q1.push(q1.front());                q1.pop();            }            q2.push(q1.front());            q1.pop();        }        return q2.front();    }    /** Returns whether the stack is empty. */    bool empty() {        return q1.empty()&&q2.empty();    }private:    queue<int>q1,q2;};
class MyStack {public:    /** Initialize your data structure here. */    MyStack() {    }    /** Push element x onto stack. */    void push(int x) {       queue<int> tmp;        while(!q.empty()){            tmp.push(q.front());            q.pop();        }        q.push(x);        while(!tmp.empty()){            q.push(tmp.front());            tmp.pop();        }    }    /** Removes the element on top of the stack and returns that element. */    int pop() {        int x=q.front();        q.pop();        return x;    }    /** Get the top element. */    int top() {        return q.front();    }    /** Returns whether the stack is empty. */    bool empty() {        return q.empty();    }private:    queue<int>q;};
原创粉丝点击