225. Implement Stack using Queues

来源:互联网 发布:文档加密软件功能 编辑:程序博客网 时间:2024/06/06 13:21

用queue实现stack。和之前有一道题用stack实现queue类似。

class MyStack {    queue<int> nums,helper;public:    /** Initialize your data structure here. */    MyStack() {    }    /** Push element x onto stack. */    void push(int x) {        nums.push(x);    }    /** Removes the element on top of the stack and returns that element. */    int pop() {        while(nums.size()>1)        {            helper.push(nums.front());            nums.pop();        }        int result=nums.front();        nums.pop();        while(!helper.empty())        {            nums.push(helper.front());            helper.pop();        }        return result;    }    /** Get the top element. */    int top() {        return nums.back();    }    /** Returns whether the stack is empty. */    bool empty() {        return nums.empty();    }};/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * bool param_4 = obj.empty(); */
0 0
原创粉丝点击