-
Notifications
You must be signed in to change notification settings - Fork 45
/
Delete_queue
87 lines (74 loc) · 1.34 KB
/
Delete_queue
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// C++ program for the above approach.
#include <bits/stdc++.h>
using namespace std;
// Function to remove an element from
// the queue
void remove(int t, queue<int>& q)
{
// Helper queue to store the elements
// temporarily.
queue<int> ref;
int s = q.size();
int cnt = 0;
// Finding the value to be removed
while (q.front() != t and !q.empty()) {
ref.push(q.front());
q.pop();
cnt++;
}
// If element is not found
if (q.empty()) {
cout << "element not found!!" << endl;
while (!ref.empty()) {
// Pushing all the elements back into q
q.push(ref.front());
ref.pop();
}
}
// If element is found
else {
q.pop();
while (!ref.empty()) {
// Pushing all the elements back into q
q.push(ref.front());
ref.pop();
}
int k = s - cnt - 1;
while (k--) {
// Pushing elements from front of q to its back
int p = q.front();
q.pop();
q.push(p);
}
}
}
// Function to print all the elements
// of the queue.
void print(queue<int> qr)
{
while (!qr.empty()) {
cout << qr.front() << " ";
qr.pop();
}
cout << endl;
}
// Driver Code
int main()
{
queue<int> q;
// Pushing into the queue
q.push(10);
q.push(20);
q.push(30);
q.push(40);
q.push(50);
q.push(60);
print(q);
// Removing 39 from the queue
remove(39, q);
print(q);
// Removing 30 from the queue
remove(30, q);
print(q);
return 0;
}