【数据结构与算法】栈的实现(链式存储)

为了让学习数据结构与算法的同学更好地理解栈,这里写出了栈的C++实现(链式存储)如果想要顺序存储,还请看本专栏上一篇文章。

#pragma once

template <typename T>
class ChainStack {
private:
	typedef struct StackNode{
		T data;
		StackNode* next;
	}StackNode,*LinkStackPtr;

	typedef struct {
		LinkStackPtr top;
		int nCount;
	}LinkStack;
	
	LinkStack m_Stack;
public:
	ChainStack();
	ChainStack(T tValue);
	~ChainStack();
public:
	bool push(T tValue);
	bool pop(T* result);
	bool clear();
};

template<typename T>
inline ChainStack<T>::ChainStack()
{
	m_Stack.top = nullptr;
	m_Stack.nCount = 0;
}

template<typename T>
inline ChainStack<T>::ChainStack(T tValue)
{
	LinkStackPtr pNewLinkNode = new StackNode;
	pNewLinkNode.data = tValue;
	pNewLinkNode.next = m_Stack.top;
	m_Stack.top = pNewLinkNode;
	m_Stack.nCount++;
}

template<typename T>
inline ChainStack<T>::~ChainStack()
{
	LinkStackPtr pNode;
	LinkStackPtr pTempNode;
	pNode = m_Stack.top;
	while (pNode) {
		pTempNode = pNode;
		pNode = pNode->next;
		std::cout << "释放数据" << pTempNode->data << "成功" << std::endl;
		delete pTempNode;
	}
	m_Stack.nCount = 0;
}

template<typename T>
inline bool ChainStack<T>::push(T tValue)
{
	LinkStackPtr pNewLinkNode = new StackNode;
	pNewLinkNode->data = tValue;
	pNewLinkNode->next = m_Stack.top;
	m_Stack.top = pNewLinkNode;
	m_Stack.nCount++;
	return true;
}

template<typename T>
inline bool ChainStack<T>::pop(T * result)
{
	if (m_Stack.nCount == 0) {
		std::cout << "当前栈为空" << std::endl;
		return false;
	}
	LinkStackPtr pTempNode = new StackNode;
	pTempNode = m_Stack.top;
	*result = pTempNode->data;
	m_Stack.top = pTempNode->next;
	delete pTempNode;
	m_Stack.nCount--;
	return true;
}

template<typename T>
inline bool ChainStack<T>::clear()
{
	LinkStackPtr pNode;
	LinkStackPtr pTempNode;
	pNode = m_Stack.top;
	while (pNode) {
		pTempNode = pNode;
		pNode = pNode->next;
		std::cout << "释放数据" << pTempNode->data << "成功" << std::endl;
		delete pTempNode;
	}
	m_Stack.top = nullptr;
	m_Stack.nCount = 0;
	return true;
}

这里只是为了让初学者了解栈的结构,如果又发现错误,还请及时指出,我们共同进步!!!

你可能感兴趣的:(数据结构与算法,算法,c++)