Simple Java Solution (Any improvements to this?)


  • 3
    S
    class MyStack {
        Queue<Integer> q = new LinkedList<Integer>();
        // Push element x onto stack.
        public void push(int x) {
            q.add(x);
            for (int i = 0; i < q.size() - 1; i++) {
                q.add(q.remove());    
            }
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            q.remove();
        }
    
        // Get the top element.
        public int top() {
            return q.peek();
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q.isEmpty();
        }
    }
    

    Any suggestions as to what could be done to make this better/more efficient or is this it?


  • 1

    Update: Has been fixed by now.

    One improvement would be to make it correct. It currently isn't. You're just lucky that the OJ never tries to have duplicates on the stack. Which is ridiculous so I'll get that changed :-)

    Efficiency-wise I think it's pretty much optimal unless you use "tricks" (like I did for my O(1) solution). Though I don't know why you test !q.isEmpty(). It can't be empty.


  • 0
    S

    Haha, good call on the !q.isEmpty() -- just got used to doing that in queue/stack questions. I'll be sure to update my solution to accommodate for duplicates.

    Thanks!

    EDIT: Updated my solution.


Log in to reply
 

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