-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path5b) Queue using stack(dequeue expensive).cpp
84 lines (67 loc) · 1.38 KB
/
5b) Queue using stack(dequeue expensive).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
82
83
84
#include<iostream>
#include<stack>
// Dequeue is expensive
using namespace std;
// Just change the property of stack
class Queue{
int size;
stack<int> st1,st2;
public:
Queue(){
size = 0;
}
void enqueue(int);
int dequeue();
bool isempty();
int getSize();
};
int Queue :: getSize(){
return size;
}
bool Queue :: isempty(){
return (st1.empty());
}
void Queue :: enqueue(int val){
size++;
st1.push(val);
}
int Queue :: dequeue(){
// Simply pop out the elements
if(st1.empty()){
return -1;
}
else{
size--;
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
// Now pop elements
int top_ele = st2.top();
st2.pop();
// Retranfer the contents into st2 from st1
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
return top_ele;
}
}
void display(Queue q){
Queue tempqueue = q ;
while(!tempqueue.isempty()){
cout << tempqueue.dequeue() << " ";
}
cout << endl;
}
int main(){
Queue qu;
for(int i=1;i<=5;i++){
qu.enqueue(i);
}
display(qu);
cout << qu.dequeue() << " got dequeued" << endl;
display(qu);
cout << "Size of Queue is : " << qu.getSize() << endl;
return 0;
}