template<class T> class LinkList
{
public:
LinkList();
~LinkList();
bool Insert(const T data);
bool Insert(const T data,const int position);
void Remove(const int position);
void Update(const T data, const int position);
void Clear();
int Getsize();
private:
struct Node
{
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
Node* head;
int size;
};
template<class T>
inline LinkList<T>::LinkList()
{
head = nullptr;
size = 0;
}
template<class T>
inline LinkList<T>::~LinkList()
{
Clear();
}
/// <summary>
/// 在链表尾部插入一个结点
/// </summary>
/// <typeparam name="T">结点数据的数据类型</typeparam>
/// <param name="data">数据</param>
/// <returns></returns>
template<class T>
inline bool LinkList<T>::Insert(const T data)
{
Node* NewNode = new Node(data);
if (NewNode == NULL)return false;//内存空间不够用
if (head == nullptr)
{
head = NewNode;
}
else
{
Node* ptr = head;
while (ptr->next!=nullptr)
{
ptr = ptr->next;
}
ptr->next = NewNode;
}
size++;
return true;
}
/// <summary>
/// 在链表中某个位置插入一个结点
/// </summary>
/// <typeparam name="T">结点数据的数据类型</typeparam>
/// <param name="data">数据</param>
/// <param name="position">位置</param>
/// <returns></returns>
template<class T>
inline bool LinkList<T>::Insert(const T data,const int position)
{
if (position > size || position < 0)return false;
Node* NewNode = new Node(data);
if (NewNode == NULL) return false;
if (position == 0) {
NewNode->next = head;
head = NewNode;
}
else {
Node* ptr = head;
for (int i = 0; i < position; i++)
{
ptr = ptr->next;
}
NewNode->next = ptr->next;
ptr->next = NewNode;
}
size++;
return true;
}
/// <summary>
/// 删除链表中某个结点
/// </summary>
/// <typeparam name="T">结点数据的数据类型</typeparam>
/// <param name="position">结点位置</param>
template<class T>
inline void LinkList<T>::Remove(const int position)
{
if (size <= position || position < 0 || size == 0)return;
if (position == 0)
{
Node* ptr = head;
head = head->next;
delete ptr;//释放这个位置的内存
size--;
return;
}
Node* ptr = head;
for (int i = 0; i < position-1; i++)
{
ptr = ptr->next;
}
Node* temp = ptr->next;//指向要删除的空间
ptr->next = temp->next;
delete temp;//释放内存
size--;
return;
}
/// <summary>
/// 更新某个结点的值
/// </summary>
/// <typeparam name="T">结点的数据的数据类型</typeparam>
/// <param name="data">数据</param>
/// <param name="position">更新结点的位置</param>
template<class T>
inline void LinkList<T>::Update(const T data, const int position)
{
if (position<0 || size == 0 || position>size)return;
Node* ptr = head;
for (int i = 0; i < position; i++)
{
ptr = ptr->next;
}
ptr->data = data;
return ;
}
/// <summary>
/// 清空链表
/// </summary>
template<class T>
inline void LinkList<T>::Clear()
{
if (size != 0) {
Node* ptr = head;
while (ptr!=nullptr)
{
Node* temp = ptr;
ptr = ptr->next;
delete temp;
}
head = nullptr;
size = 0;
}
}
/// <summary>
/// 获取链表长度
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
template<class T>
inline int LinkList<T>::Getsize()
{
return size;
}
泛型链表(自己写的)
最新推荐文章于 2024-09-02 23:29:10 发布