Write a program to implement a queue using two stacks.
Write a program to implement a queue using two stacks.
Student
I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
In this program, we implement a queue using two stacks, stack1 and stack2. The enqueue operation is straightforward, we simply push the element onto stack1.
For the dequeue operation, we first check if both stack1 and stack2 are empty, in which case the queue is empty and we cannot dequeue. If stack2 is empty, we pop all the elements from stack1 and push them onto stack2, effectively reversing the order of the elements in stack1. Finally, we pop the top element from stack2 and return it.
This approach ensures that the first element to be enqueued is always at the bottom of stack1, which becomes the top element of stack2 after the reversal.
We can construct a queue using two stacks and no other temporary variables as such:
The space complexity of this algorithm is O(1), as there are no temporary variables.
The time complexity for enqueue operation is O(1), however, the worst-case time complexity for the dequeue operation is O(n), since it requires us to move all elements from one stack to the other.
The code is implemented as follows: