Accepted Java solution


  • -1
    A

    The idea is to use two queues q1 and q2. Enqueue in one of them, let's say q1. When we need to pop or peek, we should get the last element of q1. Thus, move all elements to q2 (except from the last one in case of pop) and switch the roles of q1 and q2. We should now push any new elements to q2, until the next pop or peek and so on.

    class MyStack {
        Queue<Integer> q1 = new ArrayDeque<>();
        Queue<Integer> q2 = new ArrayDeque<>();
        boolean isOne = true;
        // Push element x onto stack.
        public void push(int x) {
            Queue<Integer> queue = queueToPush();
            queue.offer(x);
        }
    
        // Removes the element on top of the stack.
        public void pop() {
            Queue<Integer> bufffer = queueToPush();
            Queue<Integer> tmp = tempQueue();
            while (bufffer.size() > 1) {
                tmp.offer(bufffer.poll());
            }
            isOne = !isOne;
            bufffer.poll();
        }
    
        // Get the top element.
        public int top() {
            int x = -1;
            Queue<Integer> buffer = queueToPush();
            Queue<Integer> tmp = tempQueue();
            while (!buffer.isEmpty()) {
                x = buffer.peek();
                tmp.offer(buffer.poll());
            }
            isOne = !isOne;
            return x;
        }
        
        private Queue<Integer> queueToPush() {
            return isOne ? q1 : q2;
        }
        
        private Queue<Integer> tempQueue() {
            return isOne ? q2 : q1;
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q1.isEmpty() && q2.isEmpty();
        }
    }

Log in to reply
 

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