A basic java solution with O(n) push


  • 0
    L

    Note that it assumes unique numbers but it is easy to use a for loop to iterate over size.

    public class MyStack {
        private final Queue<Integer> queue = new LinkedList<>();
        
        /** Push element x onto stack. */
        public void push(int x) {
            queue.offer(x);
            while(queue.peek()!=x) {
                queue.offer(queue.poll());
            }
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return queue.poll();
        }
        
        /** Get the top element. */
        public int top() {
            return queue.peek();
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return queue.isEmpty();
        }
    }
    

Log in to reply
 

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