My accepted Java Solution using 2 Queues


  • 0
    B
    class MyStack {
        Queue<Integer> q1 = new LinkedList<Integer>();
        Queue<Integer> q2 = new LinkedList<Integer>();
        int size = 0;
        
        // Push element x onto stack.
        public void push(int x) {
            q1.add(x);
            size++;
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            while(size > 1){
                q2.add(q1.poll());
                size--;
            }
            q1.poll();
            size--;
            while(q2.peek() != null){
                q1.add(q2.poll());
                size++;
            }
        }
    
        // Get the top element.
        public int top() {
            while(size > 1){
                q2.add(q1.poll());
                size--;
            }
            int res = q1.peek();
            while(q2.peek() != null){
                q1.add(q2.poll());
                size++;
            }
            q1.add(q1.poll());
            return res;
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q1.peek() == null;
        }
    }

Log in to reply
 

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