-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueueUsingStacks.cpp
91 lines (66 loc) · 1.33 KB
/
queueUsingStacks.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
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
template<class T>
class MyQueue {
stack<T> s1;
stack<T> s2;
int numElts;
T pushPopHelper(bool pop) {
//if pop == true, pop element. Otherwise, return elt
if(s1.empty())
return NULL;
while(s1.size() > 1) {
s2.push(s1.top());
s1.pop();
}
T retVal = s1.top();
if(pop)
s1.pop();
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
if(!pop)
return retVal;
return NULL;
}
public:
MyQueue() : numElts(0) {}
void push(T val) {
s1.push(val);
numElts++;
}
void pop() {
pushPopHelper(true);
numElts--;
}
int front() {
return pushPopHelper(false);
}
bool empty() {
return !numElts;
}
int size() {
return numElts;
}
};
int main() {
MyQueue<int> mq;
queue<int> q;
for(int i = 0; i < 10; i++) {
for(int j = i + 1; j < 15; j++) {
mq.push((int) ((i * i) / j + i % j));
q.push((int) ((i * i) / j + i % j));
}
}
while(!mq.empty() && !q.empty()) {
if(mq.front() != q.front()) {
cout << "NOT EQUAL!" << endl;
return 1;
}
mq.pop(); q.pop();
}
cout << "Same queue behavior" << endl;
}