思路:栈是先进后出的数据结构,栈的基本操作为入栈和出栈。设计包含min函数的栈只要在入栈和出栈后能找到min值行,
设立一个辅助栈来存最小值,入栈时:当辅助栈为空或新入栈元素比辅助栈的栈顶元素要小时,则将新元素入辅助栈,否则将辅助栈的栈顶元素再次入栈;
出栈时只需将两个栈的栈顶元素出栈即可。
函数接口 template<class type> void StackWithMIn::push(const type&value);
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
using namespace std;
//面试题21包含min函数的栈 思路:栈是先进后出的数据结构,栈的基本操作为入栈和出栈。设计包含min函数的栈只要在入栈和出栈后能找到min值行,
//设立一个辅助栈来存最小值,入栈时:当辅助栈为空或新入栈元素比辅助栈的栈顶元素要小时,则将新元素入辅助栈,否则将辅助栈的栈顶元素再次入栈;
//出栈时只需将两个栈的栈顶元素出栈即可。
template<class type> class StackWithMin
{
public:
void pop();
void push(const type & value);
type minValue();
private:
stack<type> Stack;
stack<type> MinStack;
};
template<class type> void StackWithMin<type>::pop()
{
if(!Stack.empty()&&(!MinStack.empty()))
{
Stack.pop();
MinStack.pop();
}
}
template<class type> void StackWithMin<type>::push(const type &value)
{
Stack.push(value);
if(MinStack.empty()||value<MinStack.top())
{
MinStack.push(value);
}
else
{
MinStack.push(MinStack.top());
}
}
template<class type> type StackWithMin<type>::minValue()
{
if(!MinStack.empty())
{
return MinStack.top();
}
}
int main()
{
StackWithMin<int> testStack;
//3,4,2,1 入栈
testStack.push(3);
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.push(4);
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.push(2);
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.push(1);
cout<<"the min value is:"<<testStack.minValue()<<endl;
//1,2,4,3 出栈
testStack.pop();
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.pop();
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.pop();
cout<<"the min value is:"<<testStack.minValue()<<endl;
testStack.pop();
cout<<"the min value is:"<<testStack.minValue()<<endl;
return 0;
}