Java Solution with One Queue


  • 0
    class MyStack {
        private LinkedList<Integer> list = new LinkedList<Integer>();
        // Push element x onto stack.
        public void push(int x) {
            if (list.isEmpty()) {
                list.add(x);
            } else {
                list.add(x);
                while (list.peek() != x) {
                    int value = list.poll();
                    list.add(value);
                }
            }
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            list.poll();
        }
    
        // Get the top element.
        public int top() {
            return list.peek();
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return list.isEmpty();
        }
    }

  • 0
    J

    Your solution will not pass this test case:

    Push 1
    Push 2
    Push 1
    

    The stack should be: 1 2 1, while your queue is: 1 1 2.


  • 0
    class MyStack {
    
    private LinkedList<Integer> list = new LinkedList<Integer>();
    int len = 0;
    
    // Push element x onto stack.
    public void push(int x) {
        if (list.isEmpty()) {
            list.add(x);
            len++;
        } else {
            list.add(x);
            len++;
            int count = len - 1;
            while (count > 0) {
                int value = list.poll();
                list.add(value);
                count--;
            }
        }
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        list.poll();
    }
    
    // Get the top element.
    public int top() {
        return list.peek();
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return list.isEmpty();
    }
    

    }


  • 0

    Thanks, I realize that leetcode may just use no duplicated test case.
    How about this new solution?


  • 0
    J

    Great! The new one is perfect !


Log in to reply
 

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