232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  1. push(x) – Push element x to the back of queue.
  2. pop() – Removes the element from in front of queue.
  3. peek() – Get the front element.
  4. empty() – Return whether the queue is empty.

这种easy题很好通过的,就看有没有一些巧妙或者稍微进步的算法设计。

方法一: 最基本的思路

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) { //在stack里按queue的顺序存储,每次push都借用temp把新插入的值降到最下面
        stack<int> temp;
        while (!s.empty()) {
            temp.push(s.top());
            s.pop();
        }
        s.push(x);
        while (!temp.empty()) {
            s.push(temp.top());
            temp.pop();
        }
    }

    // Removes the element from in front of queue.
    void pop(void) {
        s.pop();
    }

    // Get the front element.
    int peek(void) {
        return s.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return s.empty();
    }

private:
    stack<int> s;

};

这个方法简单直接,就是强行在stack里保持queue的顺序,push比较麻烦,但其他的都是直接调用。

方法二:优化写法
不用保持固有的顺序,只要完成queue的规定动作返回或者删除正确的值就好。所以思路可以开阔些,给一个网上的算法:

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        _new.push(x);
    }

    void shift() {
        if (_old.empty()) {
            while (!_new.empty()) {
                _old.push(_new.top());
                _new.pop();
            }
        }
    }

    // Removes the element from in front of queue.
    void pop(void) {
        shift();
        _old.pop();
    }

    // Get the front element.
    int peek(void) {
        shift();
        return _old.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return _old.empty() && _new.empty();
    }

private:
    stack<int> _old, _new;

};

这个方法用了两个stack, 假定一个stack是按照正确顺序排列好的,pop和top都可以直接进行,push的话到另一个stack,这样的话在很多时候这些操作都实现了O(1)的复杂度。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值