Skip to content

Instantly share code, notes, and snippets.

@tolinwei
Last active January 4, 2016 04:58
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 tolinwei/8571705 to your computer and use it in GitHub Desktop.
Save tolinwei/8571705 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stack>
using namespace std;
class MyStack
{
private:
stack<int> s;
stack<int> min;
public:
void push(int v) {
s.push(v);
if (min.empty() || v <= min.top()) { //enter if first satisfy
min.push(v);
}
}
void pop() {
if (s.top() == min.top()) {
min.pop();
}
s.pop();
}
int top() {
return s.top();
}
int get_min() {
return min.top();
}
};
int main(int argc, char *argv[]) {
//test case
MyStack ms;
ms.push(2);
ms.push(3);
ms.push(1);
cout << ms.get_min() << endl;
ms.pop();
cout << ms.get_min() << endl;
ms.pop();
cout << ms.get_min() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment