得到栈中的最小值
#include <iostream> #include <stack> using namespace std; class GetMinStack{ public: void push(int x); void pop(); int top(); int getmin(); private: stack<int> S; stack<int> temp; }; void GetMinStack::push(int x) { if(S.empty()) { temp.push(x); S.push(x); } else { if(x < temp.top()) { temp.push(x); S.push(x); } else { temp.push(temp.top()); S.push(x); } } } void GetMinStack::pop() { S.pop(); temp.pop(); } int GetMinStack::top() { return S.top(); } int GetMinStack::getmin() { return temp.top(); } int main() { GetMinStack TestStack; TestStack.push(-2); cout << TestStack.top() << endl; cout << TestStack.getmin() << endl; TestStack.push(0); cout << TestStack.getmin() << endl; TestStack.push(-6); cout << TestStack.getmin() << endl; TestStack.pop(); cout << TestStack.getmin() << endl; return 0; }