Implement Stack using Two Queues

后端 未结 23 814
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  情话喂你
    2020-11-28 17:48

    Below is a very simple Java solution which supports the push operation efficient.

    Algorithm -

    1. Declare two Queues q1 and q2.

    2. Push operation - Enqueue element to queue q1.

    3. Pop operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the popped element. Swap the queues q1 and q2. Return the stored popped element.

    4. Peek operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the peeked element. Enqueue it back to queue q2 and swap the queues q1 and q2. Return the stored peeked element.

    Below is the code for above algorithm -

    class MyStack {
    
        java.util.Queue q1;
        java.util.Queue q2;
        int SIZE = 0;
    
        /** Initialize your data structure here. */
        public MyStack() {
            q1 = new LinkedList();
            q2 = new LinkedList();
    
        }
    
        /** Push element x onto stack. */
        public void push(int x) {
            q1.add(x);
            SIZE ++;
    
        }
    
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            ensureQ2IsNotEmpty();
            int poppedEle = q1.remove();
            SIZE--;
            swapQueues();
            return poppedEle;
        }
    
        /** Get the top element. */
        public int top() {
            ensureQ2IsNotEmpty();
            int peekedEle = q1.remove();
            q2.add(peekedEle);
            swapQueues();
            return peekedEle;
        }
    
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return q1.isEmpty() && q2.isEmpty();
    
        }
    
        /** move all elements from q1 to q2 except last element */
        public void ensureQ2IsNotEmpty() {
            for(int i=0; i temp = q1;
            q1 = q2;
            q2 = temp;
        }
    }
    

提交回复
热议问题