-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminStack.cpp
More file actions
50 lines (46 loc) · 702 Bytes
/
minStack.cpp
File metadata and controls
50 lines (46 loc) · 702 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
49
50
// use 2 stacks
class MinStack{
stack<int> s;
stack<int> min;
public:
void push(int val){
if ( min.empty() || val < min.top())
min.push(val);
s.push(val);
}
void pop(int val){
if (s.empty()) return;
if (s.top() == min.top())
min.pop();
s.pop();
}
int top(){
return s.top();
}
int getMin(){
return min.top();
}
};
// use 1 stack
class MinStack2{
stack<int> s;
int min;
public:
void push(int val){
if (min.empty() || val < min)
min = val;
s.push(val);
}
void pop(){
if (s.empty()) return;
if (s.top() == min)
min = std::numerical_limits<int>::min();
s.pop();
}
int top(){
return s.top();
}
int getMin(){
return min;
}
}