How to reverse the first N elements of 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 reverseQueueFirstNElements(queue<int> &q, int n) { 
    if (q.empty() == true || n > q.size() || n <= 0)
        return; 

    stack<int> Stack; 
  
    for (int i = 0; i < n; i++) { 
        Stack.push(q.front()); 
        q.pop(); 
    } 
  
    while (!Stack.empty()) { 
        q.push(Stack.top()); 
        Stack.pop(); 
    } 
  
    for (int i = 0; i < q.size() - n; i++) { 
        q.push(q.front()); 
        q.pop(); 
    } 
} 
   
int main() 
{ 
    queue<int> q;
    
    q.push(4); 
    q.push(2); 
    q.push(6); 
    q.push(1); 
    q.push(7);
    q.push(5);    
    q.push(9);
     
    printQueue(q); 
    
    reverseQueueFirstNElements(q, 4);
    
    std::cout << '\n';
    printQueue(q); 
} 
 
 
 
/*
run:
 
4 2 6 1 7 5 9 
1 6 2 4 7 5 9 
 
*/

 



answered Apr 16, 2020 by avibootz

Related questions

1 answer 249 views
1 answer 277 views
1 answer 294 views
1 answer 407 views
1 answer 232 views
232 views asked Apr 5, 2020 by avibootz
2 answers 206 views
1 answer 259 views
...