Skip to content

Instantly share code, notes, and snippets.

@kartikkukreja
Created October 27, 2016 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kartikkukreja/bd4a8b4ad36ce6e52beb96c50ce5af64 to your computer and use it in GitHub Desktop.
Save kartikkukreja/bd4a8b4ad36ce6e52beb96c50ce5af64 to your computer and use it in GitHub Desktop.
Stack with min operation
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