Java Program to Implement Stack using Two Queues

Intuition

Stack is LIFO (last in – first out) data structure, in which elements are added and removed from the same end, called top. In general stack is implemented using array or linked list, but in the current article we will review a different approach for implementing stack using queues. In contrast queue is FIFO (first in – first out) data structure, in which elements are added only from the one side – rear and removed from the other – front. In order to implement stack using queues, we need to maintain two queues q1 and q2. Also we will keep top stack element in a constant memory.

Algorithm

Push

The new element is always added to the rear of queue q1 and it is kept as top stack element

Push an element in stack

Figure 1. Push an element in stack

Java

Complexity Analysis

    • Time complexity : O(1)O(1). Queue is implemented as linked list and add operation has O(1)O(1) time complexity.

 

    • Space complexity : O(1)O(1)

 

Pop We need to remove the element from the top of the stack. This is the last inserted element in q1. Because queue is FIFO (first in – first out) data structure, the last inserted element could be removed only after all elements, except it, have been removed. For this reason we need to maintain additional queue q2, which will serve as a temporary storage to enqueue the removed elements from q1. The last inserted element in q2 is kept as top. Then the algorithm removes the last element in q1. We swap q1 with q2 to avoid copying all elements from q2 to q1.

Pop an element from stack

 

Figure 2. Pop an element from stack

Java

Complexity Analysis

  • Time complexity : O(n)O(n). The algorithm dequeues n elements from q1 and enqueues n – 1n1 elements to q2, where nn is the stack size. This gives 2n – 12n1 operations.
  • Space complexity : O(1)O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *