Algorithm Deep Dive Implement Stack using Queue Data Structure

Implement Stack using Queue Data Structure

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:

  1. The Stack class has two queue objects, q1 and q2, which are used to implement the stack.
  2. The push() method adds an item to the top of the stack. It does this by first adding the item to q2, and then moving all the items from q1 to q2. Finally, it swaps the references to q1 and q2 so that q1 now contains the updated stack.
  3. The pop() method removes and returns the top item from the stack. It does this by checking if q1 is empty, and if so, raising an error. Otherwise, it returns the item at the front of q1.
  4. The peek() method returns the top item from the stack without removing it. It does this by checking if q1 is empty, and if so, raising an error. Otherwise, it returns the item at the front of q1.
  5. The is_empty() method returns True if the stack is empty, and False otherwise.