LeetCode 225 Implement Stack using Queues

题目

class MyStack {
public:
    queue<int> q;
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        
        int len = q.size();
        
        while(len>1)
        {
            int x = q.front();
            q.pop();
            q.push(x);
            len--;
        }
        
        int x=q.front();
        q.pop();
        
        return x;
        
    }
    
    /** Get the top element. */
    int top() {
        
        int x = pop();
        q.push(x);
        return x;
        
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.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();
 */
posted @ 2020-03-04 15:10  Shendu.CC  阅读(63)  评论(0编辑  收藏  举报