2.设计包含min函数的栈

声明:此题目来自 v_JULY_v的blog,出处http://blog.csdn.net/v_july_v/article/details/6004660

代码经过本人调试,不敢保证是最优的,但应该是正确的,如果错误,希望指正,改进也可以。谢谢!!!

问题:

定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
要求函数min、push以及pop的时间复杂度都是O(1)。


答案:

//20121121
#include <iostream>
#include <stack>

using namespace std;
template<class T>
class mystacks{
public:
	void pushs(T n);
	void pops(void);
	T mins(void);
private:
	struct sn//StackNode 
	{
		T values;
		T minValue;
	};
	stack<sn> nQueue;
	sn tempSN;
};

int main()
{
	mystacks<int> st;
	st.pushs(12);
	st.pushs(34);
	st.pushs(11);
	st.pushs(45);
	st.pops();
	cout<<"mins="<<st.mins()<<endl;
	st.pops();
	cout<<"mins="<<st.mins()<<endl;
	st.pops();
	cout<<"mins="<<st.mins()<<endl;
	st.pops();
	cout<<"mins="<<st.mins()<<endl;
	st.pops();
	cout<<"mins="<<st.mins()<<endl;
	
	return 0;
}

template<class T>
void mystacks<T>::pushs(T n)
{
	if (nQueue.size()==0)
	{
		tempSN.values=n;
		tempSN.minValue=n;
		nQueue.push(tempSN);
	}
	else
	{
		tempSN.values=n;
		if (nQueue.top().minValue>n)
		{
			tempSN.minValue=n;
		}
		else
		{
			tempSN.minValue=nQueue.top().minValue;
		}
		nQueue.push(tempSN);
	}
	cout<<"pushs:"<<n<<endl;
}

template<class T>
void mystacks<T>::pops()
{
	if (nQueue.size()==0)
	{
		cout<<"stack empty"<<endl;
	}
	else
	{
		nQueue.pop();
		cout<<"stack pop"<<endl;
	}
}
template<class T>
T mystacks<T>::mins()
{
	if (nQueue.size()!=0)
	{
		return nQueue.top().minValue;
	}
	else
	{
		return NULL;
	}
}

参考文章:http://blog.csdn.net/lihappy999/article/details/7296173

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值