Thursday, April 20, 2017

Implement Queue by Two Stacks

public class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public MyQueue() {
       // do initialization if necessary
       stack1 = new Stack<>();
       stack2 = new Stack<>();
    }
   
    public void push(int element) {
        // write your code here-
        stack1.push(element);
    }

    public int pop() {
        // write your code here
        if (move()) return stack2.pop();
        else throw new NullPointerException();
    }

    public int top() {
        // write your code here
        if (move()) return stack2.peek();
        else throw new NullPointerException();
    }
    private boolean move() {
        if (stack2.isEmpty()) {
            if (stack1.isEmpty()) return false;
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return true;
    }
}

No comments:

Post a Comment