Java: Two Stacks - Consecutive READs or WRITEs are fast!


  • -2
    O

    On insertion: If application is in READ mode, switch to WRITE mode by popping off the READ queue into WRITE. Then write to the WRITE queue.

    On retrieval: If application is in WRITE mode, switch to READ mode by popping off the WRITE queue into READ. Then read from the READ queue.

    class MyQueue {
        
        Deque<Integer> left = new ArrayDeque<>(), right = new ArrayDeque<>();
        boolean isViewing = false;
        
        public void push(int x) {
            if (isViewing) while(!left.isEmpty()) right.push(left.pop());
            isViewing = false;
            right.push(x);
        }
    
        public void pop() {
            if (!isViewing) while (!right.isEmpty()) left.push(right.pop());
            isViewing = true;
            left.pop();
        }
    
        public int peek() {
            if (!isViewing) while (!right.isEmpty()) left.push(right.pop());
            isViewing = true;
            return left.peek();
        }
    
        public boolean empty() {
            return left.isEmpty() && right.isEmpty();
        }
    }

Log in to reply
 

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