📅  最后修改于: 2023-12-03 15:12:40.444000             🧑  作者: Mango
Welcome programmers! In this article, we will be discussing the solution to Problem 1 of GATE-CS-2003. This problem is related to data structures, and it tests your knowledge of implementing stacks and queues using arrays. You are required to write a program in C or C++ to implement a queue using two stacks. Sounds interesting? Let's dive into the problem details.
Here is the problem statement:
Implement a queue using two stacks s1 and s2 such that the amortized complexity of each queue operation is O(1). You can use a maximum of two stacks and a stack can use only standard push and pop operations.
To solve the problem, we need to come up with an approach to implement a queue using two stacks with O(1) amortized complexity for each queue operation. Here's one possible solution:
This approach has O(1) amortized complexity for enqueue, dequeue, and queue size operations.
Here is the implementation of the queue using two stacks in C++:
#include <iostream>
#include <stack>
using namespace std;
class Queue {
private:
stack<int> s1, s2;
int count;
public:
Queue() {
count = 0;
}
void enqueue(int x) {
s1.push(x);
count++;
}
int dequeue() {
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
int x = s2.top();
s2.pop();
count--;
return x;
}
int size() {
return count;
}
};
int main() {
Queue q;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
cout << q.dequeue() << endl;
return 0;
}
Note that we have used two stack containers from the C++ standard template library named stack
. The enqueue
function pushes the element onto the first stack s1 and increments the counter. The dequeue
function pops the element from the second stack s2, and if it's empty, it pops all elements from s1 and pushes them onto s2 in reverse order. The size
function returns the current size of the queue.
We have successfully solved Problem 1 of GATE-CS-2003, which involved implementing a queue using two stacks with O(1) amortized complexity for each queue operation. We have discussed the approach to implement the queue, along with its implementation in C++. I hope this article has helped you understand the problem and its solution. Happy coding!