leetcode232.用栈来实现队列

https://leetcode-cn.com/problems/implement-queue-using-stacks/

终于进入队列系列题目了,JAVA用Deque双端队列模拟栈,然后实现队列,先用O(n)算法

class MyQueue {
    Deque<Integer> in;
    Deque<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in = new LinkedList<Integer>();
        out = new LinkedList<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!out.isEmpty()) in.addLast(out.pollLast());
        in.addLast(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        while(!in.isEmpty()) out.addLast(in.pollLast());
        return out.pollLast();
    }
    
    /** Get the front element. */
    public int peek() {
        while(!in.isEmpty()) out.addLast(in.pollLast());
        return out.peekLast();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

思路:

1.push只对in栈进行操作,只要push就往in里面放元素

2.pop操作,由于队列是先进先出,而栈是先进后出,而in是栈,要pop in的第一个元素,需要把in的元素全部倒腾到out里去,再把out的最后一个元素pop掉,就相当于队列的pop,peek也是同理。

3.由于不确定调用empty函数前,in和out是哪个全满,所以两个一起判断。


再上一种均摊O(1)的算法

class MyQueue {
    Deque<Integer> in;
    Deque<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in = new LinkedList<Integer>();
        out = new LinkedList<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {

        in.addLast(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out.isEmpty()){
            while(!in.isEmpty()) out.addLast(in.pollLast());
        }
        return out.pollLast();
    }
    
    /** Get the front element. */
    public int peek() {
        if(out.isEmpty()) {
            while(!in.isEmpty()) out.addLast(in.pollLast());
        }
        return out.peekLast();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

这个就是不是每次push都需要in全满,out全空状态,倒腾的时机是当out为空时,把in的元素全部倒腾过来,由于out已经是队列顺序的先进先出,所以无论怎么push,只要push到in里面去,pop和peek只针对out的元素,只有out为空时,才需要把in的元素全部倒腾到out里去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值