-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode155_min_stack.cpp
67 lines (57 loc) · 1.31 KB
/
leetcode155_min_stack.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
/**
* @file leetcode155_min_stack.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2023/06/03 12:15
* @brief https://leetcode.com/problems/min-stack
*
**/
#include <iostream>
#include <stack>
using namespace std;
class MinStack {
public:
MinStack() {}
void push(int val) {
s.push(val);
if (s.size() == 1) {
smin.push(val);
} else if (smin.top() > val) {
smin.push(val);
} else {
smin.push(smin.top());
}
}
void pop() {
s.pop();
smin.pop();
}
int top() {
return s.top();
}
int getMin() {
return smin.top();
}
private:
std::stack<int> s;
std::stack<int> smin;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
int main() {
MinStack* minStack = new MinStack();
minStack->push(-2);
minStack->push(0);
minStack->push(-3);
std::cout << minStack->getMin() << std::endl;
minStack->pop();
std::cout << minStack->top() << std::endl;
std::cout << minStack->getMin() << std::endl;
delete minStack;
return 0;
}