1.

How do you implement stack using queues?

Answer»

  • A stack can be implemented using two queues. We know that a queue supports enqueue and dequeue operations. Using these operations, we need to develop push, pop operations.

  • Let stack be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Then, stack ‘s’ can be implemented in two ways:

1. By making push operation costly:


  • This method ensures that the newly entered element is always at the front of ‘q1’ so that pop operation just dequeues from ‘q1’.

  • ‘q2’ is used as auxillary queue to put every new element in front of ‘q1’ while ensuring pop happens in O(1) complexity.


  • Pseudocode:
    • Push element to stack s: Here push takes O(n) time complexity.


push(s, data):
Enqueue data to q2
Dequeue elements one by one from q1 and enqueue to q2.
Swap the names of q1 and q2
  • Pop element from stack s: Takes O(1) time complexity.
pop(s):
dequeue from q1 and return it.

2. By making pop operation costly:


  • In push operation, the element is enqueued to q1.

  • In pop operation, all the elements from q1 except the last remaining element, are pushed to q2 if it is empty. That last element remaining of q1 is dequeued and returned.


  • Pseudocode:
    • Push element to stack s: Here push takes O(1) time complexity.


push(s,data):
Enqueue data to q1
  • Pop element from stack s: Takes O(n) time complexity.
pop(s):
Step1: Dequeue every elements except the last element from q1 and enqueue to q2.
Step2: Dequeue the last item of q1, the dequeued item is stored in result variable.
Step3: Swap the names of q1 and q2 (for getting updated data after dequeue)
Step4: Return the result.


Discussion

No Comment Found