-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-stack-using-queues(AC).cpp
67 lines (58 loc) · 1.09 KB
/
implement-stack-using-queues(AC).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
// 1AC, This problem is silly.
// Why make things difficult to prove you're smart?
// You're supposed to make things easier with your brilliance.
#include <queue>
using namespace std;
class Stack {
public:
Stack() {
f = 0;
nf = !f;
}
// Push element x onto stack.
void push(int x) {
q[nf].push(x);
}
// Removes the element on top of the stack.
void pop() {
while (q[nf].size() > 1) {
q[f].push(q[nf].front());
q[nf].pop();
}
if (q[nf].size() == 1) {
q[nf].pop();
return;
}
while (q[f].size() > 1) {
q[nf].push(q[f].front());
q[f].pop();
}
f = nf;
nf = !f;
q[nf].pop();
}
// Get the top element.
int top() {
while (q[nf].size() > 1) {
q[f].push(q[nf].front());
q[nf].pop();
}
if (q[nf].size() == 1) {
return q[nf].front();
}
while (q[f].size() > 1) {
q[nf].push(q[f].front());
q[f].pop();
}
f = nf;
nf = !f;
return q[nf].front();
}
// Return whether the stack is empty.
bool empty() {
return q[f].size() + q[nf].size() == 0;
}
private:
queue<int> q[2];
int f, nf;
};