主要是在辅助的栈中push当前最小的值,若data栈pop出的数不是当前最小的,则辅助栈不动;若data栈pop出当前最小的值,则辅助栈也pop
#include <vector>
#include <iostream>
using namespace std;
template<typename object>
class minStack
{
public:
void push(object val)
{
data.push_back(val);
if(minVal.empty()||val<=minVal.back()) //需要等号
minVal.push_back(val);
}
void pop()
{
if(data.back()==minVal.back())
minVal.pop_back();
data.pop_back();
}
void printMin()
{
if(minVal.empty())
cout<<"None element"<<endl;
else
cout<<minVal.back()<<endl;
}
private:
vector<object> data;
vector<object> minVal;
};
int main()
{
minStack<int> mystack;
mystack.push(5);
mystack.printMin(); //5
mystack.push(4);
mystack.printMin(); //4
mystack.push(6);
mystack.printMin(); //4
mystack.push(3);
mystack.printMin(); //3
mystack.pop();
mystack.printMin(); //4
}