-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
queue_from_stack.cpp
56 lines (45 loc) · 1.05 KB
/
queue_from_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
// CPP program to implement Queue using
// one stack and recursive call stack.
#include <bits/stdc++.h>
using namespace std;
struct Queue {
stack<int> s;
// Enqueue an item to the queue
void enQueue(int x)
{
s.push(x);
}
// Dequeue an item from the queue
int deQueue()
{
if (s.empty()) {
cout << "Q is empty";
exit(0);
}
// pop an item from the stack
int x = s.top();
s.pop();
// if stack becomes empty, return
// the popped item
if (s.empty())
return x;
// recursive call
int item = deQueue();
// push popped item back to the stack
s.push(x);
// return the result of deQueue() call
return item;
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
return 0;
}