在常數時間內完成push,pop,getMin的棧
阿新 • • 發佈:2019-02-04
class GetMinStacke { public: void push(int x) { elements.push(x); if (minStack.empty() || x <= minStack.top()) { minStack.push(x); } } bool pop() { if (elements.empty()) { return false; } if (elements.top() == minStack.top()) { minStack.pop(); } elements.pop(); return true; } bool getMin(int &min) { if (minStack.empty()) { return false; } min = minStack.top(); return true; } private: stack<int> elements; stack<int> minStack; };