-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackUsingTwoQueue.cpp
154 lines (120 loc) · 2.4 KB
/
stackUsingTwoQueue.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/*
* stackUsingTwoQueue.cpp
* Created on: 21-May-2014
* Author: Gyaneshwar Pardhi
*/
#include<iostream>
//include queue std;
#include<queue>
using namespace std;
//define stack ADT
class Stack {
queue<int> Q1;
queue<int> Q2;
public:
// add elements in stack
void push(int value) {
if (this->Q1.empty()) {
this->Q2.push(value);
} else {
this->Q1.push(value);
}
}
//pop elements from stack
int pop() {
//move size-1 elements from non empty queue to empty queue
if (this->Q2.empty()) {
int size = Q1.size();
int i = 0;
while (i < size - 1) {
int temp = Q1.front();
Q2.push(temp);
Q1.pop();
i++;
}
int temp2 = Q1.front();
//pop nth element from non empty queue
Q1.pop();
//return nth element from non empty queue
return temp2;
} else { //move size-1 elements from non empty queue to empty queue
int size = Q2.size();
int i = 0;
while (i < size - 1) {
int temp = Q2.front();
Q1.push(temp);
Q2.pop();
i++;
}
int temp2 = Q2.front();
//pop nth element from non empty queue
Q2.pop();
//return nth element from non empty queue
return temp2;
}
}
bool isEmpty() {
//if any of the queue is empty means stack is empty
if (Q1.empty() && Q2.empty())
return 1;
else
return 0;
}
int top() {
//move n-1 elements from non empty to empty queue
if (this->Q2.empty()) {
int size = Q1.size();
int i = 0;
while (i < size - 1) {
int temp = Q1.front();
Q2.push(temp);
Q1.pop();
i++;
}
int temp2 = Q1.front();
//add nth element to empty queue
Q2.push(temp2);
Q1.pop();
//return nth element
return temp2;
} else { //move n-1 elements from non empty to empty queue
int size = Q2.size();
int i = 0;
while (i < size - 1) {
int temp = Q2.front();
Q1.push(temp);
Q2.pop();
i++;
}
int temp2 = Q2.front();
//add nth element to empty queue
Q1.push(temp2);
Q2.pop();
//return nth element
return temp2;
}
}
};
int main() {
Stack st;
//add some elements to stack
st.push(23);
st.push(24);
st.push(25);
st.push(26);
st.push(27);
//pop elements froms stack
cout << st.pop();
cout << st.pop();
//display top of stack
cout << st.top();
//again add some elements to stack
st.push(28);
st.push(29);
//display top
cout << st.top();
//again pop elements from stack
cout << st.pop();
cout << st.top();
return 0;
}