首页 > 代码库 > 实现O(1)时间复杂度带有min和max 函数的栈

实现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();
}





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