-
Notifications
You must be signed in to change notification settings - Fork 6
/
21_MinInStack.cpp
57 lines (50 loc) · 1.05 KB
/
21_MinInStack.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
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class StackWithMin {
public:
void push(const T& value);
void pop();
const T& top() const;
const T& min() const;
private:
typename stack<T> m_data;
typename stack<T> m_min;
};
template <typename T> void StackWithMin<T>::push(const T& value) {
m_data.push(value);
if(m_min.empty() || value < m_min.top())
m_min.push(value);
else
m_min.push(m_min.top());
}
template <typename T> void StackWithMin<T>::pop() {
if(!m_data.empty() && !m_min.empty()) {
m_data.pop();
m_min.pop();
}
}
template <typename T> const T& StackWithMin<T>::top() const {
if(!m_data.empty() && !m_min.empty()) {
return m_data.top();
}
}
template <typename T> const T& StackWithMin<T>::min() const {
if(!m_data.empty() && !m_min.empty()) {
return m_min.top();
}
}
int main(void)
{
StackWithMin<int> min_stack;
min_stack.push(3);
min_stack.push(4);
min_stack.push(2);
min_stack.push(1);
cout<<min_stack.min();
min_stack.pop();
cout<<min_stack.min();
cout<<min_stack.top();
return 0;
}