面试题21包含min函数的栈

思路:栈是先进后出的数据结构,栈的基本操作为入栈和出栈。设计包含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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值