-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackWithMin.h
65 lines (49 loc) · 1.14 KB
/
StackWithMin.h
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
#include <stack>
#include <assert.h>
template <typename T> class StackWithMin {
public:
StackWithMin(void) {}
virtual ~StackWithMin(void) {}
T& top(void);
const T& top(void) const;
void push(const T& value);
void pop(void);
const T& min(void) const;
bool empty() const;
size_t size() const;
private:
std::stack<T> m_data;
std::stack<T> m_min;
};
template <typename T> void StackWithMin<T>::push(const T& value) {
m_data.push(value);
if (m_min.size() == 0 || value < m_min.top())
m_min.push(value);
else
m_min.push(m_min.top());
}
template <typename T> void StackWithMin<T>::pop() {
assert(m_data.size() > 0 && m_min.size() > 0);
m_data.pop();
m_min.pop();
}
template <typename T> const T& StackWithMin<T>::min const {
assert(m_data.size() > 0 && m_min.size() > 0);
return m_min.pop();
}
template <typename T> T& StackWithMin<T>::top()
{
return m_data.top();
}
template <typename T> const T& StackWithMin<T>::top() const
{
return m_data.top();
}
template <typename T> bool StackWithMin<T>::empty() const
{
return m_data.empty();
}
template <typename T> size_t StackWithMin<T>::size() const
{
return m_data.size();
}