剑指offer——第五题

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

public class o_5s {
    Stack<Integer> stackPush = new Stack<Integer>();
    Stack<Integer> stackPop = new Stack<Integer>();

    public void add(int node) {
        stackPush.push(node);
    }

    public int poll() {
        if (stackPop.isEmpty() && stackPush.isEmpty())
            throw new RuntimeException("Queue is empty");
        else if (stackPop.isEmpty()) {
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/dl674756321/article/details/89915517