设计包含min函数的栈,要求函数min、push以及pop的时间复杂度都是O(1)

class Stack
{
private:
	struct Link
	{
		int data;
		Link* next;
		Link(const int& dat, Link* nxt):data(dat), next(nxt){}
		~Link(){}
	} *pHead;
	Link *pMinimum;
public:
	Stack():pHead(NULL), pMinimum(NULL){}
	Stack(const int& initial)
	{
		pHead = new Link(initial, NULL);
		pMinimum = new Link(initial, NULL);
	}
	~Stack()
	{
		Link* tmpNode = NULL;
		while(pHead != NULL)
		{
			tmpNode = pHead;
			pHead = pHead->next;
			delete tmpNode;
			tmpNode = NULL;
		}
		while(pMinimum != NULL)
		{
			tmpNode = pMinimum;
			pMinimum = pMinimum->next;
			if(tmpNode != NULL)
			{
				delete tmpNode;
				tmpNode = NULL;
			}
		}
	}

	bool push(const int& newData)
	{
		pHead = new Link(newData, pHead);
		if(pMinimum == NULL || pMinimum->data >= newData)
		{
			pMinimum = new Link(newData, pMinimum);
		}
		return true;
	}

	bool pop(int& iData)
	{
		if(pHead == NULL)
		{
			return false;
		}
		iData = pHead->data;
		Link* tmpNode = pHead;
		pHead = pHead->next;
		delete tmpNode;

		if(iData == pMinimum->data)
		{
			tmpNode = pMinimum;
			pMinimum = pMinimum->next;
			delete tmpNode;
		}
		return true;
	}

	bool min(int& iMinimum) const
	{
		if(pMinimum == NULL)
		{
			return false;
		}
		iMinimum = pMinimum->data;
		return true;
	}

	bool empty() const
	{
		return pHead == NULL;
	}
};

设计包含min函数的栈。
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。

要求函数min、push以及pop的时间复杂度都是O(1)。



你可能感兴趣的:(设计包含min函数的栈,要求函数min、push以及pop的时间复杂度都是O(1))