in LintCode Stack Queue ~ read.

Implement Queue by Two Stacks

LintCode-40.Implement Queue by Two Stacks

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.

This question is similar to Implement Stack by Two Queues.

public class Queue {  
    private Stack<Integer> stack;

    public Queue() {
       stack = new Stack<Integer>();
    }

    public void push(int element) {
        if (stack.isEmpty()) {
            stack.push(element);
            return;
        }

        Stack<Integer> tempStack = new Stack<Integer>();
        while (!stack.isEmpty()) {
            tempStack.push(stack.pop());
        }
        stack.push(element);

        while (!tempStack.isEmpty()) {
            stack.push(tempStack.pop());
        }
    }

    public int pop() {
        return stack.pop();
    }

    public int top() {
        return stack.peek();
    }
}

Hope this helps,
Michael