My Java Solution (Beats 74%)

  • 0
    class MyStack {
        LinkedList<Integer> list = new LinkedList<Integer>();
        int top;
        // Push element x onto stack.
        public void push(int x) {
            top = x;
        // Removes the element on top of the stack.
        public void pop() {
        //add back all the front elements at the end except last one
            for(int i=0;i<list.size()-1;i++){
            list.remove(); //remove the top which is now at the front
        // Get the top element.
        public int top() {
            return top;
        // Return whether the stack is empty.
        public boolean empty() {
            return list.size() == 0;

Log in to reply

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