How to use two queues to implement a stack (JAVA)

problem

How to use two queues to efficiently implement a stack

answer

Assuming that the two queues used to implement the stack are Q1 and Q2, you only need to define the stacking and popping operations for the stack

Push:
Insert an element in any non-empty queue.
Check whether the queue Q1 is not empty. If Q1 is empty, perform the enqueue operation on Q2;
otherwise , perform the enqueue operation on Q1.
Time complexity O(1)

Pop (POP):
Move N-1 elements to another queue, delete the last element in the current queue to complete the pop operation.
If the queue Q1 is not empty, then move n-1 elements from Q1 to Q2, and then Dequeue the last element in Q1 and return the element.
If the queue Q2 is not empty, move n-1 elements from Q2 to Q1, and then dequeue the last element of Q2 and return the element
time Complexity O(N)

Code


/**
 * 用两个队列实现栈
 */
public class StackWithTwoQueue {
    
    

    DynArrayQueue queue1;
    DynArrayQueue queue2;

    public StackWithTwoQueue() {
    
    
        queue1 = new DynArrayQueue();
        queue2 = new DynArrayQueue();
    }

    public void push(int data) {
    
    
        if (queue1.isEmpty()) {
    
    
            queue2.enQueue(data);
        } else {
    
    
            queue1.enQueue(data);
        }
    }

    public int pop() {
    
    
        int i = 0;
        int size = 0;
        if (queue2.isEmpty()) {
    
    
            size = queue1.getQueueSize();
            while (i < size - 1) {
    
    
                queue2.enQueue(queue1.deQueue());
                i++;
            }
            return queue1.deQueue();
        } else {
    
    
            size = queue2.getQueueSize();
            while (i < size - 1) {
    
    
                queue1.enQueue(queue2.deQueue());
                i++;
            }
            return queue2.deQueue();
        }
    }

}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/108804620