Answer
See the explanation
Work Step by Step
To implement a queue using two stacks, we can use one stack for enqueue operations and another stack for dequeue operations. Here's the design of the TwoStacks function:
1. Initialize two empty stacks, let's call them "stack1" and "stack2".
2. The enqueue operation can be implemented by pushing the elements onto stack1.
3. The dequeue operation can be implemented as follows:
a. If stack2 is not empty, pop the top element from stack2 and return it as the dequeued element.
b. If stack2 is empty, transfer all the elements from stack1 to stack2 in reverse order. Pop the top element from stack2 and return it as the dequeued element.
Here's the Python implementation of the TwoStacks function:
```python
class TwoStacks:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, item):
self.stack1.append(item)
def dequeue(self):
if len(self.stack2) == 0:
while len(self.stack1) > 0:
self.stack2.append(self.stack1.pop())
if len(self.stack2) == 0:
return "Queue is empty"
return self.stack2.pop()
```
Explanation:
- The `enqueue` function simply pushes the elements onto `stack1`.
- The `dequeue` function checks if `stack2` is empty. If it is, it transfers all the elements from `stack1` to `stack2` in reverse order. This ensures that the first element pushed into `stack1` becomes the first element in `stack2`, simulating the behavior of a queue. Finally, it pops and returns the top element from `stack2`.
This implementation allows us to use two stacks to achieve the functionality of a queue, with enqueue and dequeue operations having a time complexity of O(1) on average.