Approach # 01 Using 2 Stacks
class MyQueue {
stack <int> s1, s2;
public:
void push(int x) {
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
s1.push(x);
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
int pop() {
if(empty())return -1;
int d = s1.top();
s1.pop();
return d;
}
int peek() {
if(empty()) return -1;
return s1.top();
}
bool empty() {
return s1.empty();
}
};
Approach # 02 Using Single Stack
class MyQueue {
stack <int> s1;
public:
void push(int x) {
insertAtBottom(x);
}
void insertAtBottom(const int x) {
// base condition
if(s1.empty()) {
s1.push(x);
return ;
}
int temp = s1.top();
s1.pop();
// recursive call
insertAtBottom(x);
s1.push(temp);
}
int pop() {
if(empty())return -1;
int d = s1.top();
s1.pop();
return d;
}
int peek() {
if(empty()) return -1;
return s1.top();
}
bool empty() {
return s1.empty();
}
};
Q2:
Reverse Queue using recursion
void reverseQueue(queue<int>& q1) {
if(q1.empty()) return ;
int temp = q1.front();
q1.pop();
reverseQueue(q1);
q1.push(temp);
}
void print(queue<int> q) {
while(!q.empty()) {
cout << q.front() << " ";
q.pop();
}cout << endl;
}
bool checkPalindrome(string s) {
queue<char> q1, q2;
int i = 0;6
for (; i < s.size()/2; i++)
{
q1.push(s[i]);
}
if(s.size()&1) i++;
for(int j = s.size()-1; j >= i; j--) {
q2.push(s[j]);
}
return q1 == q2;
}