-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdditional2.cpp
More file actions
79 lines (70 loc) · 1.69 KB
/
Copy pathAdditional2.cpp
File metadata and controls
79 lines (70 loc) · 1.69 KB
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
#include <iostream>
#include <stack>
using namespace std;
class SpecialStack {
stack<int> s;
int minElement;
public:
void push(int x) {
if (s.empty()) {
s.push(x);
minElement = x;
}
else {
if (x >= minElement) {
s.push(x);
} else {
// store modified value
s.push(2*x - minElement);
minElement = x;
}
}
cout << x << " pushed\n";
}
void pop() {
if (s.empty()) {
cout << "Stack is empty!\n";
return;
}
int t = s.top();
s.pop();
if (t >= minElement) {
cout << "Popped: " << t << endl;
} else {
cout << "Popped: " << minElement << endl;
minElement = 2*minElement - t; // restore previous min
}
}
void getMin() {
if (s.empty()) {
cout << "Stack is empty!\n";
} else {
cout << "Minimum element = " << minElement << endl;
}
}
void peek() {
if (s.empty()) {
cout << "Stack is empty!\n";
return;
}
int t = s.top();
if (t >= minElement) {
cout << "Top element = " << t << endl;
} else {
cout << "Top element = " << minElement << endl;
}
}
};
int main() {
SpecialStack st;
st.push(5);
st.push(3);
st.getMin(); // 3
st.push(7);
st.push(2);
st.getMin(); // 2
st.pop(); // removes 2
st.getMin(); // 3
st.peek(); // top element
return 0;
}