原理很简单,借助一个辅助栈,保存最小值即可;
以下是代码和测试用例:
#include<iostream>
#include<stack>
#define MAX_STACKROOM 15
using namespace std;
//设计一个带MIN函数的栈
template<typename T>
class stackwithmin
{
public:
stackwithmin() :Size(0)
{}
void PUSH(const T&_data)
{
stack1.push(_data);
Size++;
if (stack2.empty() || _data<=stack2.top())
{
stack2.push(_data);
}
}
void POP()
{
if ( (!stack2.empty()) && (stack1.top()==stack2.top()))
stack2.pop();
if (!stack1.empty())
{
stack1.pop();
Size--;
}
}
T& TOP()
{
return stack1.top();
stack1.
}
bool Empty()
{
if (size != 0)
return false;
return true;
}
size_t SIZE()
{
return Size;
}
T& MIN()
{
if (Size!=0)
return stack2.top();
assert(false);
}
private:
size_t Size;
stack<T> stack1;
stack<T> stack2;
};
void test1()
{
stackwithmin<int> st1;
st1.PUSH(4);
st1.PUSH(2);
st1.PUSH(6);
st1.PUSH(1);
st1.PUSH(8);
cout<<st1.MIN()<<endl;
cout << st1.SIZE() << endl;
st1.POP();
cout << st1.MIN() << endl;
st1.POP();
cout << st1.MIN() << endl;
st1.POP();
cout << st1.MIN() << endl;
st1.POP();
cout << st1.MIN() << endl;
st1.POP();
cout << st1.MIN() << endl;
}
int main()
{
test1();
system("pause");
return 0;
}