-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminstack.hpp
More file actions
executable file
·48 lines (38 loc) · 965 Bytes
/
Copy pathminstack.hpp
File metadata and controls
executable file
·48 lines (38 loc) · 965 Bytes
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
/*
* minstack.hpp
*
* Created on: 2013-11-18
* Author: Rong Xiao
*/
#ifndef MINSTACK_HPP_
#define MINSTACK_HPP_
#include <vector>
#include <stack>
using std::vector;
using std::stack;
/*
* A stack template that has constant time for operations: push, pop, and min.
*/
template <class T> class MinStack : public stack<T, vector<T> > {
vector<T> _mins; // keep track of minimum on the very back
public:
MinStack() : stack<T, vector<T> >(), _mins() {
}
void push(const T& val) {
if (empty()) {
_mins.push_back(val);
} else {
curMin = _mins.back();
_mins.push_back(val<curMin ? val : curMin);
}
stack<T, vector<T> >::push(val);
}
void pop(const T& val) {
stack<T, vector<T> >::pop(val);
_mins.pop_back();
}
T min() {
return _mins.back();
}
};
#endif /* MINSTACK_HPP_ */