Apply for an additional stack space, maintain the minimum value, and perform push and pop at the same time as the data stack.
#include<iostream> #include<stack> //Member functions should not be confused with constructors // Whether the function has formal parameters has nothing to do with the return type of the function class Min{ public: void push(int x){ data.push(x); //Empty, the output is 1, clear logical judgment if(min.empty()){ min.push(x); }else{ if (x > min.top()){ x = min.top(); } min.push(x); } } void pop(){ data.pop(); min.pop(); } int top(){ return data.top(); } int getMin(){ return min.top(); } private: std::stack<int> data; std::stack<int> min; }; int main(){ Min S; S.push(2); std::cout<<S.getMin()<<std::endl; S.push(-1); std::cout<<S.getMin()<<S.top()<<std::endl; S.push(0); std::cout<<S.getMin()<<std::endl; return 0; }