美文网首页算法
用栈实现队列

用栈实现队列

作者: 一凡呀 | 来源:发表于2017-11-23 20:40 被阅读0次

    问题:

    用两个栈实现队列的基本功能

    思路:

    第一个栈正常加元素,再把第一个栈的元素pop到第二个栈,这时候就可以实现队列的功能了,即先进先出,在这里要注意两点,第一点在往第二个栈中倒的时候必须保证第二个栈为空,第二点,每次往第二个栈倒的时候必须保证第一个栈全部倒出,不满足这两点任意一点都会出错。

    代码:

    public static class TwoStacksQueue {
            private Stack<Integer> stackPush;
            private Stack<Integer> stackPop;
    
            public TwoStacksQueue() {
                stackPush = new Stack<Integer>();
                stackPop = new Stack<Integer>();
            }
    
            public void push(int pushInt) {
                stackPush.push(pushInt);
            }
    
            public int poll() {
                if (stackPop.empty() && stackPush.empty()) {
                    throw new RuntimeException("Queue is empty!");
                } else if (stackPop.empty()) {
                    while (!stackPush.empty()) {
                        stackPop.push(stackPush.pop());
                    }
                }
                return stackPop.pop();
            }
    
            public int peek() {
                if (stackPop.empty() && stackPush.empty()) {
                    throw new RuntimeException("Queue is empty!");
                } else if (stackPop.empty()) {
                    while (!stackPush.empty()) {
                        stackPop.push(stackPush.pop());
                    }
                }
                return stackPop.peek();
            }
        }
    

    相关文章

      网友评论

        本文标题:用栈实现队列

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