Last active
January 4, 2016 04:58
-
-
Save tolinwei/8571705 to your computer and use it in GitHub Desktop.
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
#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