How to reverse a queue in C++

1 Answer

0 votes
#include <bits/stdc++.h> 

using namespace std; 
  
void printQueue(queue<int>& q) { 
    while (!q.empty()) { 
        cout << q.front() << " "; 
        q.pop(); 
    } 
} 
  
void reverseQueue(queue<int>& q) { 
    stack<int> Stack; 
    while (!q.empty()) { 
        Stack.push(q.front()); 
        q.pop(); 
    } 
    while (!Stack.empty()) { 
        q.push(Stack.top()); 
        Stack.pop(); 
    } 
} 
  
int main() 
{ 
    queue<int> q; 
    
    q.push(1); 
    q.push(2); 
    q.push(3); 
    q.push(4); 
    q.push(5); 

    reverseQueue(q); 
    printQueue(q); 
} 



/*
run:

5 4 3 2 1 

*/

 



answered Apr 5, 2020 by avibootz

Related questions

1 answer 160 views
1 answer 168 views
1 answer 198 views
1 answer 188 views
3 answers 247 views
247 views asked Apr 4, 2020 by avibootz
2 answers 100 views
1 answer 168 views
...