Simple Java solution using 2 stacks!!!


  • 1
    A
    class MyQueue {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        // Push element x to the back of queue.
        public void push(int x) {
            stack1.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            stack2.pop();
            while(!stack2.isEmpty()){
                stack1.push(stack2.pop());
            }
        }
    
        // Get the front element.
        public int peek() {
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            int val = stack2.peek();
            while(!stack2.isEmpty()){
                stack1.push(stack2.pop());
            }
            return val;
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            if (stack1.isEmpty()){
                return true;
            }
            return false;
        }
    }

  • 0
    B

    Same idea, but i add a rotate method to transfer between 2 stacks. 102ms

    class MyQueue {
    int size = 0;
    Stack<Integer> end = new Stack<Integer>();
    Stack<Integer> front = new Stack<Integer>();
    // Push element x to the back of queue.
    public void push(int x) {
        this.end.push(x);
        this.size++;
    }
    
    // Removes the element from in front of queue.
    public void pop() {
        if(empty()){
            return;
        }
        if(this.front.empty()){
            rotate();
        }
        this.front.pop();
        this.size--;
    }
    
    // Get the front element.
    public int peek() {
        if(empty()){
            return 0;
        }
        if(this.front.empty()){
            rotate();
        }
        return this.front.peek();
    }
    
    // Return whether the queue is empty.
    public boolean empty() {
        return this.size==0;
    }
    private void rotate(){
        if(this.size==0){
            return;
        }
        while(!this.end.empty()){
            this.front.push(this.end.pop());
        }
    }
    

    }


Log in to reply
 

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