queue 模拟 stack

来源:互联网 发布:内存兼容性测试软件 编辑:程序博客网 时间:2024/05/22 11:44
class Stack {public:    // Push element x onto stack.    queue<int>A;    queue<int>B;    void push(int x) {        A.push(x);    }    // Removes the element on top of the stack.    void pop() {        while(B.size()){            B.pop();        }        int ans;        while(A.size()){            int t=A.front();            A.pop();            if(A.size()){                B.push(t);            }                  }        while(B.size()){            A.push(B.front());                B.pop();                    }    }    // Get the top element.    int top() {         while(B.size()){            B.pop();        }        int ans;        while(A.size()){            int t=A.front();            A.pop();            if(!A.size())            ans=t;            B.push(t);                              }        while(B.size()){            A.push(B.front());                B.pop();                    }        return ans;    }    // Return whether the stack is empty.    bool empty() {        return A.size()==0;            }};

0 0