How to implement a stack using queue
First and foremost we need to remember two things:
a) a stack operates in LIFO mode, i.e; the last element pushed in is always popped out first. This indicates that only one end of the structure is available for access, while the other end is always closed.
b) a queue operates in FIFO mode, i.e; the the element pushed in first is always popped out first. This indicates that both ends of the structure are available for access. If the one end is used for pushing in, the other end is used for popping out.
So, to implement a stack using queue, we need to operate queue in such a way that every time a new element is pushed in , it have to the reach other end of the structure, so that while popping out of the queue, elements pops out in order, they are pushed in, just like stack.
To achieve this goal we have to follow this algorithm:
a) enqueue the new element.
b) dequeue the remaining queue.
c) enqueue all the elements popped out of the queue in the order as they are popped out.
a) dequeue one element from the queue.