-
Notifications
You must be signed in to change notification settings - Fork 1
/
155_Min_Stack.cpp
57 lines (42 loc) · 970 Bytes
/
155_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
// https://leetcode.com/problems/min-stack/
// https://leetcode.com/problems/min-stack/discuss/1948714/C%2B%2B-Using-an-Extra-Stack-or-Super-Simple-()
#include <iostream>
#include <stack>
using namespace std;
class MinStack
{
private:
stack<int> stk;
stack<int> minStk;
public:
void push(int val)
{
stk.push(val);
if (minStk.empty() or val <= minStk.top())
minStk.push(val);
}
void pop()
{
if (stk.empty()) // although, it's guarnteed that stack will not be empty, but still it's a good practice to check it before pop(), top() and getMin()
return;
if (stk.top() == minStk.top())
minStk.pop();
stk.pop();
}
int top()
{
if (stk.empty())
return -1;
return stk.top();
}
int getMin()
{
if (minStk.empty())
return -1;
return minStk.top();
}
};
int main()
{
return 0;
}