剑指offer:用两个栈实现一个队列(java)

/**
 *题目:
 *      用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 * 思路:
 *      全部压入一个栈,然后弹出到另外一个栈
 */
public class P68_TwoStacksToQueue {
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();
    public void push(int node) {
        stack1.push(node);
    }
    public int pop() {
        //先考虑stack2是否为空,再考虑stack1是否为空
        if (!stack2.empty()) {
            return stack2.pop();
        }
        else if (!stack1.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            } return stack2.pop();
        }
        else
            throw new RuntimeException("queue is empty");

    }

}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/82462968