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();
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值