leetcode 225 & 232.Implement Stack using Queues & Implement Queue using Stacks

突然听人说起有同学做了某游戏公司的笔试题,遇到如何用栈实现队列,想起来自己在半年前做过用队列实现栈和用栈实现队列,现在回忆起来,只记得如果用栈实现队列,忘了用队列实现栈了,在此记录一下。
总所周知,栈是先进先出,队列是先进后出。
对于一个序列来说,一个序列进入队列之后,再出来,序列顺序不变。
在进入栈之后,再出来,序列顺序相反了。
无论是用栈实现队列,还是用队列实现栈,实际上考虑的都是如何将这个序列弄反

从此思路出发,对于一个队列来说,如果将序列弄反,当然是在每次插入数字的时候,都把整个队列放在新插入数字的后面,这一点用队列是很方便实现的。当然,这样每次push操作的复杂度都在O(n),是很浪费时间的,这个思路的循环相当于又利用一个队列的资源
下面是代码:

class MyStack {
public:
    /** Initialize your data structure here. */
    queue<int> que;
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        que.push(x);
        for(int i=1;i<que.size();++i)
        {
            que.push(que.front());
            que.pop();
        }        
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int result=que.front();
        que.pop();
        return result;  
    }

    /** Get the top element. */
    int top() {
        return que.front();
    }

    /** Returns whether the stack is empty. */
    bool empty() {
        return que.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();
 */

至于如何用栈实现队列,可以用两个栈来实现两次序列反转,在这边就不贴代码了,难度也不大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值