链表数据结构的C++实现:类模板实现线性表的链式存储

类的定义

在类的内部包含一个结构体,结构体包含一个指向下一结点的指针,以及一个数据域,用于存储插入链表的用户数据。

#pragma once
#include <iostream>
using namespace std;

template<typename MyType>
class LinkedList
{
public:
	LinkedList();
	~LinkedList();
public:
	int get_length();
	MyType get_data(int pos);
	int insert(MyType& node, int pos);
	MyType delet(int pos);
	void clear();
public:
	typedef struct ListNode
	{
		struct ListNode* next;
		MyType data;
	}ListNode;
private:
	int length;
	ListNode* head;
};

成员函数的实现

template<typename MyType>
LinkedList<MyType>::LinkedList()
{
	this->head = new ListNode;
	this->head->next = NULL;
	this->length = 0;
}

template<typename MyType>
LinkedList<MyType>::~LinkedList()
{
	ListNode* pCurrent = this->head;
	while (pCurrent != NULL)
	{
		ListNode* pTemp = pCurrent;
		pCurrent = pCurrent->next;
		delete pTemp;
	}
	this->length = 0;
}

template<typename MyType>
int LinkedList<MyType>::get_length()
{
	return this->length;
}

template<typename MyType>
MyType LinkedList<MyType>::get_data(int pos)
{
	ListNode* pCurrent = this->head;
	for (int i = 0; i < pos; i++)
	{
		pCurrent = pCurrent->next;
	}
	return pCurrent->next->data;
}

template<typename MyType>
int LinkedList<MyType>::insert(MyType& node, int pos)
{
	ListNode* pCurrent = this->head;
	for (int i = 0; i < pos; i++)
	{
		pCurrent = pCurrent->next;
	}
	ListNode* pNode = new ListNode;
	pNode->data = node;
	pNode->next = pCurrent->next;
	pCurrent->next = pNode;
	this->length++;
	return 0;
}

template<typename MyType>
MyType LinkedList<MyType>::delet(int pos) 
{
	ListNode* pCurrent = this->head;
	for (int i = 0; i < pos; i++)
	{
		pCurrent = pCurrent->next;
	}
	MyType temp_data = pCurrent->next->data;
	ListNode* pTemp = pCurrent->next;
	pCurrent->next = pCurrent->next->next;
	delete pTemp;
	this->length--;
	return temp_data;
}

template<typename MyType>
void LinkedList<MyType>::clear()
{
	ListNode* pCurrent = this->head;
	while (pCurrent != NULL)
	{
		ListNode* pTemp = pCurrent;
		pCurrent = pCurrent->next;
		delete pTemp;
	}
	this->head = new ListNode;
	this->head->next = NULL;
	this->length = 0;
}

因为链表的结点是动态分配的,插入一个数据,就用动态构造一个结点,并把要插入的数据存到结点的数据域。所以,在插入元素和删除元素的时候需要使用new和delete来管理内存。

C语言实现链表请参考文章

【数据结构】线性表的链式存储(链表)API及实现icon-default.png?t=M276https://blog.csdn.net/qq_43471489/article/details/123771559另外,代码资源已经上传,可在我的资源免费下载。

posted @ 2022-04-07 07:15  Mindtechnist  阅读(17)  评论(0编辑  收藏  举报  来源