用栈实现队列入队出队操作

public class Queue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public Queue() {
       stack1=new Stack<Integer>();
       stack2=new Stack<Integer>();
    }
    
    public void push(int element) {
        if(stack1.empty()){
            int t;
            while(!stack2.empty()){
                t=stack2.pop();
                stack1.push(t);
            }
        }
        stack1.push(element);
    }

    public int pop() {
        if(stack2.empty()){
            int t;
            while(!stack1.empty()){
                t=stack1.pop();
                stack2.push(t);
            }
        }
        return stack2.pop();
    }

    public int top() {//top()返回队列头元素
        int t;
        if(!stack2.empty()){
            t=stack2.pop();
            stack2.push(t);
            return t;
        }else{
            while(!stack1.empty()){
                t=stack1.pop();
                stack2.push(t);
            }
            t=stack2.pop();
            stack2.push(t);
            return t;
        }

    }
}

主要思想:

采用两个栈:

stack1用来执行入栈操作;stack2用来执行出栈操作

入栈时,先判断stack1是否为空,如果为空,且stack2有元素,将stack2元素依次出栈并push到stack1中;stack1再执行入栈(及队列入队)操作。

出栈时,先判断stack2是否为空,如果为空,且stack1有元素,将stack1元素依次出栈并push到stack2中;stach2再执行出栈(及队列出队)操作。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值