Saved Bookmarks
| 1. |
How to implement a queue using stack? |
|
Answer» A queue can be implemented using two stacks. Let q be the queue andstack1 and stack2 be the 2 stacks for implementing q. We know that stack supports push, pop, and peek operations and using these operations, we need to emulate the operations of the queue - enqueue and dequeue. Hence, queue q can be implemented in two methods (Both the methods use auxillary space complexity of O(n)): 1. By making enqueue operation costly:
While stack1 is not empty: Push everything from stack1 to stack2. Push data to stack1 Push everything back to stack1.
If stack1 is empty then error else Pop an item from stack1 and return it 2. By making the dequeue operation costly:
Push data to stack1
If both stacks are empty then raise error. If stack2 is empty: While stack1 is not empty: push everything from stack1 to stack2. Pop the element from stack2 and return it. |
|