A basic java solution with O(n) push

  • 0

    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) {
            while(queue.peek()!=x) {
        /** 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.