Java solution with two queues


  • 0
    V
    public class MyStack {
        
        Queue<Integer> q0;
        Queue<Integer> q1;
        int head;
    
        /** Initialize your data structure here. */
        public MyStack() {
            q0 = new LinkedList<>();
            q1 = new LinkedList<>();
            head = 0;
        }
        
        /** Push element x onto stack. */
        public void push(int x) {
            if (head==0) {
                if (!q1.isEmpty()) q0.add(q1.poll());
                q1.add(x);
            } else {
                if (!q0.isEmpty()) q1.add(q0.poll());
                q0.add(x);
            }
            
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            int retVal = 0;
            if (head==0) {
                while (q0.size()>1) q1.add(q0.poll());
                retVal = q1.poll();
                head = 1;
            } else {
                while (q1.size()>1) q0.add(q1.poll());
                retVal = q0.poll();
                head = 0;
            }
            return retVal;
        }
        
        /** Get the top element. */
        public int top() {
            if (head==0) {
                if (!q1.isEmpty()) return q1.peek();
                else return q0.peek();
            } else {
                if (!q0.isEmpty()) return q0.peek();
                else return q1.peek();
            }
        }
        
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return q0.isEmpty() && q1.isEmpty();
        }
    }
    

Log in to reply
 

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