[算法题]用两个栈实现队列

来源:互联网 发布:hp1005扫描软件下载 编辑:程序博客网 时间:2024/06/01 08:03

用两个栈实现队列

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

思路:
1. Stack是先进后出,而队列是先进先出。
2. Stack1用于插入,运用另一个Stack2插入从Stack1中弹出的数据后,数据的顺序就会反转。

    Stack<Integer> stack1 = new Stack<Integer>();    Stack<Integer> stack2 = new Stack<Integer>();    public void push(int node) {        stack1.push(node);    }    public int pop() {        if(!stack2.isEmpty()){            return stack2.pop();        }        while(!stack1.isEmpty() && stack2.add(stack1.pop())){            //System.out.println("add to stack2 ");        }        return stack2.pop();    }