面试题7(1):用2个栈实现队列

来源:互联网 发布:北方民族大学网络 编辑:程序博客网 时间:2024/06/06 01:59

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

解题:当push值时,不敢栈1中有值没值,压入栈1即可。

当pop值时,如果栈2中没值,栈1中有值;则要弹出的是栈1中栈底的值。则需要把栈1中的值依次弹出压入栈2中,再弹出栈2栈顶的值即是栈1栈底的值。如果栈2中有值,则直接弹出栈2栈顶的值即可。

public class Use2StackImplQueue {    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()) {            while (!stack1.isEmpty()) {                stack2.push(stack1.pop());            }        }        return stack2.pop();    }}



原创粉丝点击