美文网首页
经典面试题--两个栈实现一个队列

经典面试题--两个栈实现一个队列

作者: 瀚海网虫 | 来源:发表于2020-10-08 00:27 被阅读0次

    1. 基本的实现原理

    栈: 先进后出
    队列: 后进先出

    采用一个压入栈 pushStack,一个弹出栈 popStack。
    压入栈依次弹出,再压入弹出栈。这样弹出栈出栈时,刚好整体上实现了先进先出。


    image.png

    为了防止次序发生混乱:

    1. 如果pushStack 压入完,开始向popStack 压数据,必须等pushStack的数据全部压入popStack后,才可进行其他操作
    2. 如果弹出栈 popStack 不为空,意味着还有未弹栈的数字,此时,不能再向弹出栈中压入数据,而是直接弹出即可。

    2. 代码实现

    public class TestQueueAndStack {
        public static void main(String[] args) {
            MyQueue queue = new MyQueue();
            queue.push(1);
            queue.push(2);
            queue.push(3);
            int i = 1;
            try {
                System.out.println("队列出队的第" + i + "个是:" + queue.poll());
                System.out.println("队列出队的第" + (i + 1) + "个是:" + queue.poll());
                System.out.println("队列出队的第" + (i + 2) + "个是:" + queue.poll());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    class MyQueue {
        Stack<Integer> popStack;
        Stack<Integer> pushStack;
        public MyQueue() {
            popStack = new Stack<Integer>();
            pushStack = new Stack<Integer>();
        }
        
        void push(Integer i) {
            pushStack.push(i);
        }
         
        int poll() throws Exception {
            if (popStack.isEmpty() && pushStack.isEmpty()) {
                 throw new Exception("队列中没有数据");
            } else if (popStack.isEmpty()) {  //一旦开始压入popStack 栈,必须确保全部压入
                while (!pushStack.isEmpty()) {
                    popStack.push(pushStack.pop());
                }
            }
            return popStack.pop();
        }
    }
    

    运行结果:

    队列出队的第1个是:1
    队列出队的第2个是:2
    队列出队的第3个是:3
    

    相关文章

      网友评论

          本文标题:经典面试题--两个栈实现一个队列

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