-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackImplementation.cpp
More file actions
65 lines (57 loc) · 1.48 KB
/
StackImplementation.cpp
File metadata and controls
65 lines (57 loc) · 1.48 KB
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
class MinStack {
private:
vector<int> stack;
int minIndex;
public:
/** initialize your data structure here. */
MinStack() {
minIndex = -1;
}
void push(int x) {
if(minIndex == -1){
stack.push_back(x);
minIndex = stack.size()-1;
}
else{
stack.push_back(x);
if(stack[minIndex] > x){
minIndex = stack.size()-1;
}
}
}
void pop() {
if(!stack.empty()){
if(minIndex == stack.size()-1 && stack.size()>1){
int minElem = stack[0];
minIndex = 0;
for(int i =stack.size()-2; i>0; i--){
if(minElem > stack[i]){
minElem = stack[i];
minIndex = i;
}
}
}
stack.pop_back();
if(stack.empty()){
minIndex =-1;
}
}
}
int top() {
if(!stack.empty())
return stack.back();
}
int getMin() {
// cout << minIndex <<endl;
if(!stack.empty() && minIndex!=-1)
return stack[minIndex];
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/