剑指Offer 用两个栈实现队列


import java.util.LinkedList;
import java.util.Stack;

/**
 * 用两个栈实现队列
 */

public class JZ005TwoStacksImpAQueue {

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

    public void push(int node) {
        stack1.push(node);
    }

    public int pop() throws Exception {
        if (stack1.isEmpty() && stack2.isEmpty()) {
            throw new Exception("two stacks are empty");
        }
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    /*
    用两个栈实现队列
    总结:
        1、需要考虑的是在stack2出栈的时候,stack1这时候有进栈
        2、栈和队列的区分:
            - 栈:先进后出
            - 队列:先进先出
        3、延伸:用两个队列实现栈 网上找到了一个非常好的Blog:https://blog.csdn.net/cherrydreamsover/article/details/80466781
     */



    LinkedList<Integer> queue1 = new LinkedList<>();
    LinkedList<Integer> queue2 = new LinkedList<>();

    public void sPop(int node) {
        queue1.add(node);
    }

    public int sPush() throws Exception {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            throw new Exception("queue is null");
        }
        while (queue1.size() > 1) {
            queue2.add(queue1.poll());
        }
        int result = queue1.poll();
        while (!queue2.isEmpty()) {
            queue1.add(queue2.poll());
        }
        return result;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼王呵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值