My Java Solution with only editing the push method


  • 2
    K
    class MyQueue {
    private Stack<Integer> stack = new Stack<>();
    
    // Push element x to the back of queue.
    public void push(int x) {
        Stack<Integer> tmp = new Stack<>();
        int len = stack.size();
        for (int i = 0; i < len; i++) {
            tmp.push(stack.peek());
            stack.pop();
        }
        stack.add(x);
        for (int i = 0; i < len; i++) {
            stack.add(tmp.peek());
            tmp.pop();
        }
    }
    
    // Removes the element from in front of queue.
    public void pop() {
        if (stack != null) stack.pop();
    }
    
    // Get the front element.
    public int peek() {
        return (Integer) stack.peek();
    }
    
    // Return whether the queue is empty.
    public boolean empty() {
        return stack == null ? true : stack.isEmpty();
    }
    

    }


  • 0
    K

    With each push, your code iterate through the existing queue 2 times. it can be slow if the queue becomes huge.


Log in to reply
 

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