Created
October 27, 2016 03:49
-
-
Save kartikkukreja/bd4a8b4ad36ce6e52beb96c50ce5af64 to your computer and use it in GitHub Desktop.
Stack with min operation
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
template <typename T> | |
class StackWithMin { | |
private: | |
stack< pair<T, T> > S; | |
public: | |
void push(T& x) { | |
S.push(pair<T, T>(x, S.empty() ? x : min(x, S.top().second))); | |
} | |
T pop() { | |
if (S.empty()) | |
throw "stack empty"; | |
pair<T, T> top = S.top(); S.pop(); | |
return top.first; | |
} | |
T getMin() { | |
if (S.empty()) | |
throw "stack empty"; | |
return S.top().second; | |
} | |
int size() { | |
return S.size(); | |
} | |
bool empty() { | |
return S.empty(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment