-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path24_3_queue_using_stack_1.cpp
70 lines (58 loc) · 1.23 KB
/
24_3_queue_using_stack_1.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
#include "bits/stdc++.h"
using namespace std;
/*
Approach 1:
Using 2 stacks, here deQueue operation costly
enQueue Operation:
Push x to Stack1.
deQueue Operation:
1.If both stacks are empty then print error.
2.If stack2 is empty, while stack1 is not empty, push everything from stack1 to stack2.
3.Pop the element from stack2 and return it.
*/
class que{
stack<int> s1;
stack<int> s2;
public:
void push(int x){
s1.push(x); //cost is O(1)
}
int pop(){ //cost is O(n)
if(s1.empty() and s2.empty()){
cout<<"Queue is empty\n";
return -1;
}
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
int topval=s2.top();
s2.pop();
return topval;
}
bool empty(){
if(s1.empty() and s2.empty()){
return true;
}
return false;
}
};
int32_t main()
{
que q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.pop()<<"\n";
q.push(5);
cout<<q.pop()<<"\n";
cout<<q.pop()<<"\n";
cout<<q.pop()<<"\n";
cout<<q.pop()<<"\n";
cout<<q.pop()<<"\n";
cout<<q.empty()<<endl;
return 0;
}