Created
April 11, 2020 15:32
-
-
Save iamsurya/8c29d545bc43d3241b56058408f22f7f to your computer and use it in GitHub Desktop.
MinStack C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Leetcode https://leetcode.com/problems/min-stack | |
// What's a min stack? A min stack is a stack (first in, last out) that also tracks the minimum value at any given point of time. | |
// push, pop, top and min element need to be constant time. | |
class StackNode{ | |
public: | |
int val; | |
int minval; | |
StackNode(int x, int min): val(x), minval(min) {}; | |
}; | |
class MinStack { | |
public: | |
/** initialize your data structure here. */ | |
stack<StackNode> customstack; | |
int minval; | |
MinStack() { | |
minval = INT_MAX; | |
} | |
void push(int x) { | |
StackNode node(x, minval); | |
customstack.push(node); | |
if(x < minval) minval = x; | |
} | |
void pop() { | |
StackNode tops = customstack.top(); | |
if(tops.val == minval) minval = tops.minval; | |
customstack.pop(); | |
} | |
int top() { | |
StackNode tops = customstack.top(); | |
return tops.val; | |
} | |
int getMin() { | |
return minval; | |
} | |
}; | |
/** | |
* 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(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment