-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_kqu.cpp
57 lines (50 loc) · 909 Bytes
/
reverse_kqu.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Given an integer K and a queue of integers, we need to reverse the order of the first K elements of the queue, leaving the other elements in the same relative order.
*/
#include <bits/stdc++.h>
using namespace std;
void display(queue<int> q){
if(q.empty()){
cout << "Empty queue\n";
return;
}
cout << "Updated queue: ";
while(!q.empty()){
cout << q.front() << " ";
q.pop();
}
cout << endl;
}
void reverse_firstk(queue<int> &q, int k){
if(q.empty() || k > q.size()) return;
stack<int> s;
int n = q.size();
for(int i = 0; i < k; i++)
{
s.push(q.front());
q.pop();
}
while(!s.empty()){
q.push(s.top());
s.pop();
}
for(int i = 0; i < (n-k); i++){
q.push(q.front());
q.pop();
}
}
int main(){
int n,x;
cin >> n;
queue<int> q;
for(int i = 0; i < n; i++)
{
cin >> x;
q.push(x);
}
cout << "Enter k: ";
cin >> x;
reverse_firstk(q, x);
display(q);
return 0;
}