-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathreverse first k - Copy.cpp
67 lines (58 loc) · 1.24 KB
/
reverse first k - Copy.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
58
59
60
61
62
63
64
65
66
67
// C++ program to reverse first
// k elements of a queue.
#include <bits/stdc++.h>
using namespace std;
/* Function to reverse the first
K elements of the Queue */
void reverseQueueFirstKElements(int k, queue<int>& Queue)
{
if (Queue.empty() == true || k > Queue.size())
return;
if (k <= 0)
return;
stack<int> Stack;
/* Push the first K elements
into a Stack*/
for (int i = 0; i < k; i++) {
Stack.push(Queue.front());
Queue.pop();
}
/* Enqueue the contents of stack
at the back of the queue*/
while (!Stack.empty()) {
Queue.push(Stack.top());
Stack.pop();
}
/* Remove the remaining elements and
enqueue them at the end of the Queue*/
for (int i = 0; i < Queue.size() - k; i++) {
Queue.push(Queue.front());
Queue.pop();
}
}
/* Utility Function to print the Queue */
void Print(queue<int>& Queue)
{
while (!Queue.empty()) {
cout << Queue.front() << " ";
Queue.pop();
}
}
// Driver code
int main()
{
queue<int> Queue;
Queue.push(10);
Queue.push(20);
Queue.push(30);
Queue.push(40);
Queue.push(50);
Queue.push(60);
Queue.push(70);
Queue.push(80);
Queue.push(90);
Queue.push(100);
int k = 5;
reverseQueueFirstKElements(k, Queue);
Print(Queue);
}