-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathqueue_with_2stacks.cpp
More file actions
56 lines (46 loc) · 883 Bytes
/
queue_with_2stacks.cpp
File metadata and controls
56 lines (46 loc) · 883 Bytes
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
#include <stack>
#include <iostream>
using namespace std;
class Queue
{
public:
void enQueue(int x)
{
//push item onto the first stack
s1.push(x);
}
int deQueue()
{
if (s1.empty() && s2.empty())
{
cout << "queue is empty" << endl;
return -1;
}
//if s2 is empty, move all items from s1
if (s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
//return top item from s2
int x = s2.top();
s2.pop();
return x;
}
private:
stack<int> s1, s2;
};
int main()
{
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << endl;
cout << q.deQueue() << endl;
cout << q.deQueue() << endl;
return 0;
}