π One-stop destination for all your technical interview Preparation π
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
push(int x)
Pushes element x to the back of the queue.pop()
Removes the element from the front of the queue and returns it.peek()
Returns the element at the front of the queue.empty()
Returns true if the queue is empty, false otherwise.Notes:
class MyQueue{
stack<int> input, output;
public:
// Initialize tha data structure
MyQueue(){}
// Push element x to the back of the queue
void push(int x){
input.push(x);
}
// Removes the element from the front of the queue and returns it.
int pop(){
int temp = peek();
output.pop();
return temp;
}
// Get the front element.
int peek(){
if (output.empty())
{
while (input.empty() == false)
{
output.push(input.top());
input.pop();
}
}
return output.top();
}
// Return whether the queue is empty.
bool empty(){
return (input.empty() && output.empty());
}
};
/*
Your MyQueue object will be instantiated and called as such:
MyQueue* obj = new MyQueue();
obj->push(x);
int param_2 = obj->pop();
int param_3 = obj->peek();
bool param_4 = obj->empty();
*/
I was asked in the internship interview of a company two years ago.
The application for this implementation is to separate read & write of a queue in multi-processing. One of the stack is for read, and another is for write. They only interfere each other when the former one is full or latter is empty.
When thereβs only one thread doing the read/write operation to the stack, there will always one stack empty. However, in a multi-thread application, if we have only one queue, for thread-safety, either read or write will lock the whole queue. In the two stack implementation, as long as the second stack is not empty, push operation will not lock the stack for pop.