Leetcode225 用队列实现栈

【方法一】

用一个辅助队列,每当有元素push进“栈”,则需要把队列的front位置给它空出来,方便后面直接pop()和top(),因此我们可以做两次搬家操作,来获得一个新的队列:

class MyStack {
private:
    queue<int> q;
    queue<int> tmp;
public:
    
    
    /** Push element x onto stack. */
    void push(int x) {
        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 res = q.front();
        q.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

【方法二】那么有没有复杂度更低的方法,比如一次直接到位的办法呢?想想其实没有必要用那个辅助队列,在每次push()操作时,我们直接从队列头开始,把每一个元素复制到队尾,然后删除队头的这个元素,这样push进来的新元素就到了front的位置:

class MyStack {
private:
    queue<int> q;
public:
    
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
        for(int i=0;i<q.size()-1;++i){
            q.push(q.front());
            q.pop();
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int res = q.front();
        q.pop();
        return res;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

猜你喜欢

转载自blog.csdn.net/zpznba/article/details/83987480