my simple JAVA solution ** and easy-understand ** use two stack


  • 0
    F

    here is my solution:

    class MyQueue {

    Stack<Integer> head = new Stack<Integer>();
    Stack<Integer> tail = new Stack<Integer>();
    // Push element x to the back of queue.
    public void push(int x) {
        while(!tail.empty()){
            head.push(tail.pop());
        }
        tail.push(x);
    }
    
    // Removes the element from in front of queue.
    public void pop() {
        while(!head.empty()){
            tail.push(head.pop());
        }
        tail.pop();
    }
    
    // Get the front element.
    public int peek() {
        while(!head.empty()){
            tail.push(head.pop());
        }
        return tail.peek();
    }
    
    // Return whether the queue is empty.
    public boolean empty() {
        return head.empty() && tail.empty();
    }
    

    }


Log in to reply
 

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