So simple that it's a little stupid solution, O(n) push, O(1) others.


  • 0
    J
    class MyStack {
    private Queue<Integer> queue = new LinkedList<Integer>();
    public void push(int x) {
        int t = queue.size();
        queue.offer(x);
        while(t-- > 0) {
            queue.offer(queue.poll());
        }
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        queue.poll();
    }
    
    // Get the top element.
    public int top() {
        return queue.peek();
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return queue.isEmpty();
    }
    }

  • -3
    F

    There was a suggestion in the problem's description to use a deque.
    So, you could use java.util.Deque as a stack and reduce complexity of push(x) to O(1).


  • 0
    T

    That wasn't the suggestion, it violates this part:

    as long as you use only standard operations of a queue.


Log in to reply
 

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