leetcode 225. Implement Stack using Queues

可以用两个队列倒来倒去,保留最后一个,pop效率成了线性的。

我这里用一个队列,自己倒自己,pop和top都是线性,时间换空间吧。

class MyStack {
public:
    deque<int> q;
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push_back(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int size = q.size();
        for (int i = 0; i < size - 1; i++) {
            int t = q.front();
            q.pop_front();
            q.push_back(t);
        }
        int ret = q.front();
        q.pop_front();
        return ret;
    }
    
    /** Get the top element. */
    int top() {
        int size = q.size();
        for (int i = 0; i < size - 1; i++) {
            int t = q.front();
            q.pop_front();
            q.push_back(t);
        }
        int ret = q.front();
        q.pop_front();
        q.push_back(ret);
        return ret;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

 

posted on 2018-02-06 11:23  willaty  阅读(82)  评论(0编辑  收藏  举报

导航