I have implemented a Queue using 2 Stacks in Java where I follow this algorithm:
enQueue(x)
Push x to stack1deQueue()
1) If both stacks are empty then error.
2) If stack2 is empty while stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it.
Now, the problem here is that the first deQueue() operation is very slow (since it transfers everything to stack2). Can we modify the algorithm somehow so that deQueue is O(1) always? Are there other alternatives?
You can swap the two stacks.
deQueue()
stack1 is not empty, swap the two stacks.
stack2 and return it.
Using a swap, the operation is always O(1)
If you need a FIFO queue, use two queues. Only use a stack if you need LIFO behaviour.
If this is the case, there is no difference between using one queue or two queues, so you may as well use just one queue. If you are using threads, use an ExecutorService which wraps a Queue and a thread pool.