Tuesday, 17 November 2015

C++ program to Reverse a Queue.

/*
program to reverse the queue using stack. Just deque the queue and push each dequeued element into the stack. After this pop the elements of the stack and enqueue into the queue.
*/
#include<bits/stdc++.h>
using namespace std;
void show_content(queue<int> q)
{
    queue<int> temp_queue=q;
    cout<<"Contents of the Queue are:\n";
    if(q.size()==0)
    {
        cout<<"No elements in Queue\n";
    }
    else
    {
        while(!temp_queue.empty())
        {
            int d=temp_queue.front();
            temp_queue.pop();
            cout<<d<<" ";
        }
    }
    cout<<"\n";
}
int main()
{
    queue<int> q;
    q.push(23);
    q.push(13);
    q.push(54);
    q.push(85);
    q.push(71);
    q.push(59);
    q.push(44);
    q.push(42);
    q.push(12);
    q.push(17);
    q.push(92);
    q.push(94);
    q.push(59);
    q.push(66);
    show_content(q);
    stack<int> stk;
    while(!q.empty())
    {
        int data=q.front();
        q.pop();
        stk.push(data);
    }
    while(!stk.empty())
    {
        int data=stk.top();
        stk.pop();
        q.push(data);
    }
    show_content(q);
    return 0;
}


No comments:

Post a Comment