实现O(1)时间复杂度带有min和max 函数的栈

仅仅是演示实现。不考虑栈使用的数据结构是vector 还是其它容器。

代码例如以下


#include <iostream>
#include <vector>

using namespace std;

template <class T>
class minMaxStack
{
public:
	minMaxStack()
	{
		DataStack = new vector<T>;
		minStack = new vector<int>;
		maxStack = new vector<int>;
	}
	~minMaxStack()
	{
		delete DataStack;
		delete minStack;
		delete maxStack;
	}
	bool isEmpty()
	{
		return DataStack->size() == 0;
	}
	void push(T data)
	{
		
		if (isEmpty())
		{
			DataStack->push_back(data);
			minStack->push_back(0);
			maxStack->push_back(0);
		}
		else
		{
			DataStack->push_back(data);
			int minIndex = *(minStack->end()-1);
			int maxIndex = *(maxStack->end()-1);
			int min = *(DataStack->begin() + minIndex);
			int max = *(DataStack->begin() + maxIndex);
			if (min > data)
			{
				minStack->push_back(DataStack->size() - 1);
			}
			else
			{
				minStack->push_back(minIndex);
			}
			if (max > data)
			{
				maxStack->push_back(maxIndex);
			}
			else
			{
				maxStack->push_back(DataStack->size() - 1);
			}
		}
	}

	T getTop()
	{
		return *(DataStack->end()-1);
	}
	void pop()
	{
		if (isEmpty())
		{
			return;
		}
		minStack->erase(minStack->end()-1);
		maxStack->erase(maxStack->end()-1);
		DataStack->erase(DataStack->end()-1);
	}
	T max()
	{
		return *(DataStack->begin() + (*(maxStack->end()-1)));
	}
	T min()
	{
		return *(DataStack->begin() + (*(minStack->end()-1)));
	}
	void printStack()
	{
		cout << "栈顶:" << getTop() << endl;
		cout << "最小:" << min() << endl;
		cout << "最大:" << max() << endl;
		cout << "\n\n";
	}
private:
	vector<T> * DataStack;
	vector<int> * minStack;
	vector<int> * maxStack;
};



void main()
{
	minMaxStack<int> st;
	st.push(6);
	st.printStack();
	st.push(17);
	st.printStack();
	st.push(7);
	st.printStack();
	st.push(3);
	st.printStack();
	st.pop();
	st.printStack();
	st.pop();
	st.printStack();
	st.pop();
	st.printStack();
	cin.get();
}





本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5303437.html,如需转载请自行联系原作者

上一篇:零基础入门python3.7 ——基础知识总结(七)集合(set)


下一篇:论程序的成长—— 你写的代码有生命力吗?