用栈实现队列

用两个栈模拟一个队列的情况
创建两个栈A B,A专门用来入队列,B专门用来出队列

1.实现入队列:先把B中的元素搬运到A中,然后把新元素往A中入栈即可

2.实现出队列:先把A中的元素搬运到B中,然后对B直接出栈即可

3.取栈顶元素:先把A中的元素搬运到B中,然后取B的栈顶元素即可

4.判空:A B都为空

代码如下:

public class queueByStack {
    private Stack<Integer> A = new Stack<>();
    private Stack<Integer> B = new Stack<>();

   //入队列
    public void push(int x){
        //1.把B中元素都搬运到A中
        while(!B.isEmpty()){
            int tmp = B.pop();
            A.push(tmp);
        }
        //把新元素往A中入栈即可
        A.push(x);
    }

    //出队列
    public Integer pop(){
        //1.如果为空直接返回null
        if(empty()){
            return null;
        }
        //2.把A中的元素搬运到B中
        while (A.isEmpty()){
            int tmp = A.pop();
            B.push(tmp);
        }
        //3.针对B进行出栈
        return B.pop();
    }

    //取栈顶元素
    public Integer peek(){
        //1.如果为空,直接返回null
        if(empty()){
            return null;
        }
        //2.把A中的元素搬运到B中
        while(A.isEmpty()){
            int tmp = A.pop();
            B.push(tmp);
        }
        //3.取出B的栈顶元素
        return B.peek();
    }
    //判空
    public boolean empty(){
        return A.isEmpty() && B.isEmpty();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值