-
Notifications
You must be signed in to change notification settings - Fork 0
/
minStack
73 lines (67 loc) · 1.33 KB
/
minStack
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
68
69
70
71
72
73
#include <bits/stdc++.h>
class minStack
{
stack<int> st;
int minValue;
void getMin(stack<int> &st,int& minimum){
if(st.empty()){
return;
}
int ele = st.top();
st.pop();
if(ele < minimum){
minimum = ele;
}
getMin(st,minimum);
st.push(ele);
return;
}
public:
minStack()
{
minValue = 100000;
}
void push(int num)
{
if(st.empty()){
minValue = num;
st.push(num);
return;
}
if(num<minValue){
minValue = num;
}
st.push(num);
return;
}
int pop()
{
if(st.empty()){
return -1;
}
int element = st.top();
st.pop();
if(element == minValue){
int mini = 100001;
getMin(st,mini);
minValue = mini;
return element;
}else{
return element;
}
}
int top()
{
if(st.empty()){
return -1;
}
return st.top();
}
int getMin()
{
if(st.empty()){
return -1;
}
return minValue;
}
};