leetcode 用栈实现队列

这题以前写过,不过效率很低,看过剑指offer后突然发现用两个栈实现如此简单:

这里简单记录下,想看详细的可以参考剑指offer。

现在假设有三个元素:{a,b,c}

插入:直接插入stack1。此时stack1有{a,b,c},stack2为空。

抛出:由于之前是直接插入stack1,队列是先进先出,所有最先被抛出的应该是a,而a在stack1中的最栈部,不能直接抛出,此时借助stack2,把stack1的元素逐个弹出并压入stack2,则此时顺序正好和之前的相反,stack1为空,stack2为{c,b,a},这时可以弹出stack2的栈顶元素a了。

抛出a后,stack2的元素为{c,b},如果还要抛出,直接抛出stack2的b即可。此时stack2的元素为{c},stack1为空。

由此得出:当stack2不为空时,stack2的栈顶元素时最先进入队列的元素,直接弹出stack2的栈顶元素。当stack2为空时,把stack1的元素逐个弹出并压入stack2。

如果接下来再压入一个元素d,还是压入stack1,下次抛出时,由于stack2不为空,直接弹出栈顶元素c,c比d先进入队列,因此两个栈并不会矛盾。

截图:

代码实现:


/**
 * @author yuan
 * @date 2019/1/30
 * @description
 */
public class MyQueue {

    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    /** Initialize your data structure here. */
    public MyQueue() {

    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        stack1.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!stack2.isEmpty()) {
            return stack2.pop();
        } else {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }
    }

    /** Get the front element. */
    public int peek() {
        if (!stack2.isEmpty()) {
            return stack2.peek();
        } else {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            return stack2.peek();
        }
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

   

}

效率很不错了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值