剑指Offer----面试题21:包含min函数的栈

题目:


定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。

分析:


使用两个栈,一个数据栈,一个辅助栈,数据栈中存放数据,辅助栈中依次存放较小的值。


源代码:


头文件StackWithMin.h
#ifndef STACKWITHMIN_H
#define STACKWITHMIN_H

#include<stack>

namespace StackWithMinSpace
{
	class ThrowError{};

	template<typename T>
	class StackWithMin
	{
	public:
		StackWithMin(void){}
		virtual ~StackWithMin(){}

		T &top();
		const T &top() const;

		void pop();
		void push(T const &t);
		const T &min() const;

		bool empty();
		int size();

	private:
		std::stack<T> dataStk;
		std::stack<T> minStk;
	};


}
#endif

实现文件StackWIthMin.cpp
#include"StackWithMin.h"

namespace StackWithMinSpace
{
	template<typename T>
	bool StackWithMin<T>::empty()
	{
		return dataStk.empty();
	}

	template<typename T>
	int StackWithMin<T>::size()
	{
		return dataStk.size();
	}

	template<typename T>
	void StackWithMin<T>::push(T const &t)
	{
		dataStk.push(t);

		if (minStk.empty() || t < minStk.top())
			minStk.push(t);
		else
			minStk.push(minStk.top());
	}

	template<typename T>
	void StackWithMin<T>::pop()
	{
		if (dataStk.empty())
		{
			throw ThrowError{};
		}

		dataStk.pop();
		minStk.pop();
	}

	//const T &min() const;
	template<typename T>
	const T & StackWithMin<T>::min() const
	{
		if (minStk.empty())
		{
			throw ThrowError{};
		}
		
		return minStk.top();
	}

	template<typename T>
	T &StackWithMin<T>::top()
	{
		if (dataStk.empty())
		{
			throw ThrowError{};
		}

		return dataStk.top();
	}

	template<typename T>
	const T &StackWithMin<T>::top() const
	{
		if (dataStk.empty())
		{
			throw ThrowError{};
		}

		return dataStk.top();
	}
}

测试文件:
//#include"StackWithMin.h"
#include"StackWithMin.cpp"
#include<iostream>

using std::cout;
using std::endl;

using namespace StackWithMinSpace;

void test11()
{
	StackWithMin<int> stk;
	stk.push(5);
	stk.push(4);
	stk.push(2);
	stk.push(2);
	stk.push(1);
	
	cout << "栈的大小" << stk.size() << endl;
	cout << "最小的数字为:" << stk.min() << endl;

	stk.pop();

	cout << "栈的大小" << stk.size() << endl;
	cout << "最小的数字为:" << stk.min() << endl;

	stk.pop();

	cout << "栈的大小" << stk.size() << endl;
	cout << "最小的数字为:" << stk.min() << endl;

	stk.pop();

	cout << "栈的大小" << stk.size() << endl;
	cout << "最小的数字为:" << stk.min() << endl;
}

int main()
{
	test11();
	cout << endl;

	system("pause");
	return 0;
}


运行结果:

栈的大小5
最小的数字为:1
栈的大小4
最小的数字为:2
栈的大小3
最小的数字为:2
栈的大小2
最小的数字为:4

请按任意键继续. . .


另外转载一篇<模板类的定义和声明为什么要写在一起>的文章,欢迎阅读!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值