Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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 133 views
1 answer 163 views
1 answer 150 views
1 answer 301 views
1 answer 128 views
128 views asked Apr 5, 2020 by avibootz
1 answer 147 views
1 answer 196 views
...