-
Notifications
You must be signed in to change notification settings - Fork 0
/
minStack.cpp
90 lines (77 loc) · 1.7 KB
/
minStack.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
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <class T>
class Stack {
public:
T pop() {
if(data.empty()) return T();
T temp = data.back();
data.pop_back();
if(temp == min) {
minCount--;
if(minCount == 0) {
calculateMin();
}
}
return temp;
}
void push(T value) {
data.push_back(value);
if(value == min) {
minCount++;
}
else if(value < min) {
minCount = 1;
min = value;
}
}
T getMin() {
return min;
}
void output() {
for(auto rit = data.rbegin(); rit != data.rend(); ++rit) {
cout << *rit << " ";
}
cout << "\n";
}
private:
void calculateMin() {
minCount = 0;
min = T();
for(auto value : data) {
if(minCount == 0) {
min = value;
minCount = 1;
}
else if(min > value) {
min = value;
minCount = 1;
}
else if(min == value) {
minCount++;
}
}
}
vector<T> data;
T min;
int minCount;
};
int main()
{
Stack<int> stack;
cout << stack.pop() << "\n";
stack.push(1);
stack.push(2);
stack.push(-8);
stack.push(14);
stack.push(100);
stack.output();
cout << stack.getMin() << "\n";
stack.pop();
stack.pop();
stack.pop();
cout << stack.getMin() << "\n";
}