用两个栈实现一个队列

来源:互联网 发布:数据库约束是什么意思 编辑:程序博客网 时间:2024/06/10 15:28

题:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:栈是先进后出,队列是先进先出,所以用栈1来入栈,用栈2来出栈。

  • 对于入栈:首先判断栈2是否为空,如果不为空,先把栈2所有的元素倒入栈1,然后再把需要入栈的元素入到栈1;其他情况,则直接把需要入栈的元素入到栈1。
  • 对于出栈:首先判断两个栈是否都为空,为空则抛出空指针异常。不为空则再判断栈2是否为空,如果栈2不为空,则直接从栈2pop出一个元素返回;如果栈2为空,则把栈1的元素依次倒入栈2,这里可以做一个优化,就是在栈1只剩一个元素的时候,直接从栈1pop出最后一个元素返回,而不需要先把所有元素都倒入栈2然后从栈2pop出栈顶元素返回,这样子就减少了一步入栈操作。

代码:

    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {        if(!stack2.isEmpty()) {            while (!stack2.isEmpty()){                stack1.push(stack2.pop());            }        }        stack1.push(node);    }    public int pop() {        if(stack1.isEmpty() && stack2.isEmpty())            throw new NullPointerException();        if(!stack2.isEmpty())            return stack2.pop();        while (stack1.size() > 1){            stack2.push(stack1.pop());        }        return stack1.pop();    }

呕心沥血写出来的,转载请一定注明出处!

原创粉丝点击