forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_Queue_content_using_Stack.cpp
81 lines (68 loc) · 1.4 KB
/
Reverse_Queue_content_using_Stack.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
Problem -
To reverse the content of a queue using only a stack.
Algorithm -
First we pop each element from the queue and push it element by element into the stack. We keep doing this until the queue is empty.
Then we pop each element from the stack and push it element by element into the queue. We keep doing this until the stack is empty.
We get the content of queue reversed.
*/
#include <bits/stdc++.h>
using namespace std;
// Displays all content of queue
void Q_Display(queue <int> q)
{
while (!q.empty())
{
cout << q.front() << " ";
q.pop();
}
}
// Reverses content of queue using stack
void reverse_queue(queue <int> *q)
{
stack <int> s;
// Poping from queue and pushing into stack
while (!q->empty())
{
s.push(q->front());
q->pop();
}
// Poping from stack and pushing into queue
while (!s.empty())
{
q->push(s.top());
s.pop();
}
}
int main()
{
queue <int> q;
int temp, n;
cout << "Enter queue size : ";
cin >> n;
while (n--)
{
cout << "\nEnter a number : ";
cin >> temp;
q.push(temp);
}
cout << "\nOriginal queue : ";
Q_Display(q);
reverse_queue(&q);
cout << "\nReversed queue : ";
Q_Display(q);
}
/*
Test run example -
Enter queue size : 5
Enter a number : 1
Enter a number : 2
Enter a number : 3
Enter a number : 4
Enter a number : 5
Original queue : 1 2 3 4 5
Reversed queue : 5 4 3 2 1
Time and Space Complexity -
Time - O(n)
Space - O(n)
*/