Implement Queue by Two Stacks

Question:

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element), pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Lesson Learned:

  • 所有field都要初始化才能使用,否则会抛出NullPointerException.
public class Queue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public Queue() {
       // do initialization if necessary
       // !!!!要初始化
       stack1 = new Stack<Integer>();
       stack2 = new Stack<Integer>();
    }

    public void push(int element) {
        // write your code here
        while (!stack2.empty()) {
            stack1.push(stack2.pop());
        }
        stack1.push(element);
    }

    public int pop() {
        // write your code here
        if (stack1.empty) {
            throw new NoSuchElementException;
        }
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        int pop = stack2.peek();
        stack2.pop();
        return pop;
    }

    public int top() {
        // write your code here
        if (stack1.empty) {
            throw new NoSuchElementException;
        }
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
        int pop = stack2.peek();
        return pop;
    }
}