In: Computer Science
[C++]
Write an algorithm to transfer the elements from queue Q1 to queue Q2, so that the contents in Q2 will be in reverse order as they are in Q1 (e.g. if your queue Q1 has elements A, B, and C from front to rear, your queue Q2 should have C, B, and A from front to rear). Your algorithm must explicitly use an additional stack to solve the problem. Write your algorithm in pseudo code first.
CODE
#include <bits/stdc++.h>
using namespace std;
void display(queue<char>& q)
{
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
}
void reverse(queue<char>& q)
{
stack<char> s;
while (!q.empty()) {
s.push(q.front());
q.pop();
}
while (!s.empty()) {
q.push(s.top());
s.pop();
}
}
int main()
{
queue<char> q;
q.push('A');
q.push('B');
q.push('C');
reverse(q);
display(q);
}