Easy Java solution, just edit push() method


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

    }


  • 7
    Y

    I think your time complexity is worse than the solution with two stacks. In the two stack solution, each element is pushed and popped exactly twice, giving an amortized time complexity for push and popping O(1)


  • 0
    E

    you are right


  • 0
    N

    想法不错,但实现起来太消耗时间。


  • 5

    I don't know why there are so many people like this answer. Honestly, this is a really bad answer and he should receive -26 instead of 26. Really disappointed when I open and read it. Waste my time


  • 0
    L

    so you pour elements out to get the bottom and pour them back to the stack again?


  • 0
    N

    The solution with two stacks is definitely better.


  • 0
    P

    Very slow. Too many useless operations performed when push.


Log in to reply
 

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