美文网首页剑指offer4J
剑指offer4J【C2 P9】两个栈实现队列,两个队列实现栈

剑指offer4J【C2 P9】两个栈实现队列,两个队列实现栈

作者: sxqiong | 来源:发表于2020-11-23 13:19 被阅读0次

题目

两个栈实现队列

题解

比较简单 就不多解释了 看代码吧

class Queue {
    private Deque<Integer> stackIn = new LinkedList<>();
    private Deque<Integer> stackOut = new LinkedList<>();
    private int defaultValue = -1;

    public void offer(int value) {
        stackIn.push(value);
    }

    public int poll() {
        if (stackOut.isEmpty()) {
            if (stackIn.isEmpty()) {
                return defaultValue;
            } else {
                while (!stackIn.isEmpty()) {
                    stackOut.push(stackIn.pop());
                }
            }
        }
        return stackOut.pop();
    }
}

题目

两个队列实现栈

题解

也不难 不浪费时间了

class Stack {
    private Deque<Integer>[] queues = new Deque[]{new LinkedList<Integer>(), new LinkedList<Integer>()};
    private int status = 0;
    private int defaultValue = -1;

    public void push(int value) {
        queues[status % 2].offer(value);
    }

    public int pop() {
        while (true) {
            int index = status % 2;
            int next = (status + 1) % 2;
            if (queues[index].size() < 1) return defaultValue;
            while (queues[index].size() > 1)
                queues[next].offer(queues[index].poll());
            status=(status+1)%2;
            return queues[index].poll();
        }
    }
}

总结: 这类题目考验对数据结构的理解,与灵活性,不要死记硬背,练死劲,讲究四两拨千斤,接化发,更不能搞偷袭,耍小聪明来凑够字数 哈

源码: 剑指offer4J

相关文章

  • 用两个栈实现队列,用两个队列实现堆栈

    参考:剑指Offer面试题7(Java版):用两个栈实现队列与用两个队列实现栈 用两个栈实现队列stack1作为入...

  • 剑指Offer(五)

    剑指Offer(五) 用两个栈实现队列 题目描述: 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列...

  • 2019-03-14

    【编程题】 用两个栈实现队列 【剑指系列】用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为...

  • LeetCode | 面试题09. 用两个栈实现队列【剑指Off

    LeetCode 面试题09. 用两个栈实现队列【剑指Offer】【Easy】【Python】【栈】【队列】 问题...

  • 栈和队列

    两个栈实现队列 两个队列实现栈

  • 两个栈实现一个队列

    《剑指offer》面试题9:两个栈实现队列 题目:用2个栈实现一个队列,完成队列的push和pop操作 思路:栈1...

  • 剑指offer第二版-9.用两个栈实现队列

    本系列导航:剑指offer(第二版)java实现导航帖 面试题9:用两个栈实现队列 题目要求:用两个栈,实现队列的...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 队列、栈

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

  • 剑指offer第二版-用队列实现一个栈

    本系列导航:剑指offer(第二版)java实现导航帖 用队列实现一个栈题目要求:用两个队列,实现栈的从队尾插入元...

网友评论

    本文标题:剑指offer4J【C2 P9】两个栈实现队列,两个队列实现栈

    本文链接:https://www.haomeiwen.com/subject/tboriktx.html