Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
/**
* 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();
*/
class MinStack {
public:
int StckTop;
int stck[10000], minStck[10000];
/** initialize your data structure here. */
MinStack() {
StckTop = -1;
}
void push(int x) {
if(StckTop == -1){
StckTop++;
stck[StckTop] = x;
minStck[StckTop] = x;
}else{
int mini = minStck[StckTop];
StckTop++;
stck[StckTop] = x;
if(x < mini){
minStck[StckTop] = x;
}else{
minStck[StckTop] = mini;
}
}
}
void pop() {
if(StckTop == -1){
cout << "Stack underflow";
}else{
StckTop--;
}
}
int top() {
if(StckTop == -1){
cout << "Stack underflow";
return INT_MIN;
}
return stck[StckTop];
}
int getMin() {
if(StckTop == -1){
cout << "Stack underflow";
return INT_MIN;
}
return minStck[StckTop];
}
};
0 comments:
Post a Comment