队列实现栈和栈实现队列

两个队列实现一个栈和两个栈实现一个队列

参考博客

两个队列实现一个栈

​ push方法:直接将新的元素放入queue1的队尾。
​ pop方法:两个队列一定是一个队列为空,一个队列非空;将非空的队列中的元素放到另一个队列,直到只剩下一个元素,将这个元素弹出即可。
在这里插入图片描述

public class Queue2Stack{
    private LinkedList<Integer> queue1 = new LinkedList();
    private LinkedList<Integer> queue2 =  new LinkedList();
    public void push(int item){
        queue1.addLast(item);
    }
    public Integer pop(){
        if(queue1.size()+queue2.size()>1){
            if(queue1.isEmpty()){
                while(queue2.size()>1){
                    queue1.addLast(queue2.removeFirst());
                }
                return queue2.removeFirst();
            }
            if(queue2.isEmpty()){
                while(queue1.size()>1){
                    queue2.addLast(queue1.removeFirst());
                }
                return queue1.removeFirst();
            }
        }
        return null;
    }
}

两个栈实现一个队列

​ add方法:新add的元素直接放在stack1。
​ get方法:如果stack2为空,需要将所有stack1的元素放到stack2中;如果stack2不为空,直接从stack2中弹出最上面的元素即可。
在这里插入图片描述

public class Stack2Queue{
    private Stack<Integer> stack1 = new Stack();
    private Stack<Integer> stack2 = new Stack();
    public void add(int item){
        stack1.push(item);
    }
    public Integer get(){
        if(stack1.size()+stack2.size()>0){
            if(stack2.isEmpty()){
                while(!stack1.isEmpty()){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值