用栈实现队列

本篇博客探讨如何利用两个栈A和B来实现队列的功能。入队操作时,若B栈非空,则将B栈元素转移至A栈;出队操作时,若A栈非空,则将A栈元素转移至B栈并出队。关键在于始终保持一个栈为空,以保持队列的正确顺序。

题目网址:https://leetcode-cn.com/problems/implement-queue-using-stacks/
这题的思路与”用队列实现栈“是类似的。
这里我们需要两个栈来辅助我们实现队列,两个栈分别是A和B
A栈:负责入队列操操作,B栈负责出队列操作

入队列操作:需要先判断一下B是不是空栈,如果是空栈,就直接push,如果不是空,就需要将B的元素push到A中,保持原有队列的顺序。

出队列操作:需要判断一下A栈是不是空栈,如果A栈不是空,就需要将A的元素都push到B中,这样A栈底的元素就跑到B栈顶去了,只要对B进行出栈就实现了出队列的操作。如果A是空,直接对B操作

取栈顶元素操作:如上,唯一的不同是,B栈顶的元素无需出栈

在这里插入图片描述
这题的关键是无论怎么是哪个操作,必有一个栈是空的。

class MyQueue {

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

    }
    Stack<Integer> A = new Stack<>();
    Stack<Integer> B = new Stack<>();
    /** Push element x to the back of queue. */
    public void push(int x) {
        if(!B.isEmpty()){
            int ret = B.pop();
            A.push(ret);
        }
        A.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(A.isEmpty()&&B.isEmpty()){
            return 0;
        }
        while (!A.isEmpty()){
            int ret = A.pop();
            B.push(ret);
        }
        int result = B.pop();
        return result;
    }

    /** Get the front element. */
    public int peek() {
        if(A.isEmpty()&&B.isEmpty()){
            return 0;
        }
        while (!A.isEmpty()){
            int ret = A.pop();
            B.push(ret);
        }
        return B.peek();
    }

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

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值