-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathMin Stack.cpp
More file actions
52 lines (46 loc) · 708 Bytes
/
Min Stack.cpp
File metadata and controls
52 lines (46 loc) · 708 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
51
52
#include<bits/stdc++.h>
using namespace std;
class MinStack
{
stack<int> st;
stack<int> minSt;
public:
void push(int x)
{
st.push(x);
if (minSt.empty() || minSt.top() >= x)
minSt.push(x);
}
void pop()
{
if (st.empty())
return;
int cur = st.top();
st.pop();
if (minSt.top() == cur)
minSt.pop();
}
int top()
{
return st.top();
}
int getMin()
{
return minSt.top();
}
};
int main()
{
MinStack minStack;
minStack.push(3);
minStack.push(5);
cout << minStack.getMin() << "\n";
minStack.push(2);
minStack.push(1);
cout << minStack.getMin() << "\n";
minStack.pop();
cout << minStack.getMin() << "\n";
minStack.pop();
cout << minStack.top() << "\n";
return 0;
}