In: Computer Science
((by C++ ))Write a program that will reverse the content of a Queue using the following standard queue operations.
For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data-structure which can serve the purpose. According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should be the first element of the reversed queue. Using the new data structure to store the elements of the queue temporarily should:
Input Format
The program should accept N series of integer values where 1 < N < 10 separated by a space and stored in a queue. If the input N integer exceeds the allowed number of input the program should display an error message.
Example Input
Enter N Integer values: 1 2 3 4 5 6 7 8 9 10 |
Output Format
The program should display the reverser order of the queue elements in a single line separated by a space. (Note: that only queue standards operations can be used to display the queue elements).
Example Output
Reverse Queue: 10 9 8 7 6 5 4 3 2 1 |
C++ PROGRAM :
#include <iostream>
#include<stack>
#include<queue>
using namespace std;
int main() {
queue<int>q;
cout<<"Enter N integer values: ";
int n;
int count=0;
// take the input until N is in range.
while(cin>>n&&count<10)
{
q.push(n);
count++;
}
//condition to check if number exceeds N series of
integers.
if(cin>>n)
{
cout<<"Error! The input N exceeds the allowed number of
input.";
return 0;
}
//using data Structure STACK which follows LIFO order.
stack<int>s;
while(!q.empty())
{
int t=q.front();
q.pop();
s.push(t);
}
//poping the elements from the Stack , back into the
queue.
while(!s.empty())
{
int top=s.top();
s.pop();
q.push(top);
}
//printing the reverse content from the queue.
cout<<"\nReverse Queue: ";
while(!q.empty())
{
cout<<q.front()<<" ";
q.pop();
}
return 0;
}
EXAMPLE :