My easy-understanding Java solution using 2 stacks

  • 0

    class MyQueue {

    Stack<Integer> stack = new Stack<Integer>();
    // Push element x to the back of queue.
    public void push(int x) {
        if(stack.size() == 0) stack.push(x);
            Stack<Integer> temp = new Stack<Integer>();
            while(!stack.isEmpty()) temp.push(stack.pop());
            while(!temp.isEmpty())  stack.push(temp.pop());
    // Removes the element from in front of queue.
    public void pop() {
    // Get the front element.
    public int peek() {
        return stack.peek();
    // Return whether the queue is empty.
    public boolean empty() {
        return stack.isEmpty();


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.