leetcode255.用队列实现栈

https://leetcode-cn.com/problems/implement-stack-using-queues/

class MyStack {
    Deque<Integer> cur,pre;
    /** Initialize your data structure here. */
    public MyStack() {
        cur = new LinkedList<>();
        pre = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        pre.addLast(x);
        while(!cur.isEmpty()) pre.addLast(cur.pollFirst());
        while(!pre.isEmpty()) cur.addLast(pre.pollFirst());
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int res = cur.peekFirst();
        cur.pollFirst();
        return res;
    }
    
    /** Get the top element. */
    public int top() {
        return cur.peekFirst();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return cur.isEmpty();
    }
}

用队列实现栈不能用上一题的思路,两个队列相互倒腾,因为队列是先进先出,就算把队列a的值倒腾到队列b,也不过是再造了一个队列a。

思路:

1.cur队列存储的是维护好的栈顺序。

2.每次push之前,先把元素存在备用pre队列头(此时pre为空),然后把cur的元素全都导到pre中,形成push的x在pre的头中,实现了后入先出

3.要维护push函数,就要在push函数最后把pre中的元素全都导回cur,保证每次调用push,pre都为空,cur为倒序的队列(相当于栈)


可以优化使用一个队列,cur.size知道cur队列的size,把队列的先进元素pollLast然后再addFirst,只留下cur队列中的最后一个元素不操作,让最后一个元素保持在cur队列的第一个,实现了cur队列的先进后出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值