Stacks are a fundamental data structure that follow the Last-In-First-Out (LIFO) principle. This principle is exactly opposite of First-In-First-Out (FIFO) principle on Queue data structure is based on. While stacks can be implemented directly using an array or a linked list, they can also be constructed using two queues.
Implementing a stack with queues involves maintaining two queues, where one queue is used to store the elements, while the other queue is used to reverse the order of the elements when popping from the stack. Below is a basic program which demonstrates implementing a stack data structure using two queue objects:
Loading code…
Here’s how the implementation works:
- The
Stackclass has two queue objects,q1andq2, which are used to implement the stack. - The
push()method adds an item to the top of the stack. It does this by first adding the item toq2, and then moving all the items fromq1toq2. Finally, it swaps the references toq1andq2so thatq1now contains the updated stack. - The
pop()method removes and returns the top item from the stack. It does this by checking ifq1is empty, and if so, raising an error. Otherwise, it returns the item at the front ofq1. - The
peek()method returns the top item from the stack without removing it. It does this by checking ifq1is empty, and if so, raising an error. Otherwise, it returns the item at the front ofq1. - The
is_empty()method returnsTrueif the stack is empty, andFalseotherwise.