一、存放数据的结构体
首先需要自定义一个存放数据的结构体模板,假定结构体中需要存放的数据类型有int,double,char和任意类型的数组,因此就有
template <typename U>
struct LNode {
int a;
double b;
char c;
U* array;
};
考虑到结构体内有数组,在之后初始化的工作和查找数据的时候需要重新写循环,因此在结构体中重载赋值和等于运算符。
void operator= (const U a)const {
int num = sizeof(a) / sizeof(a[0]);
array = new U[num];
for (int i = 0; i < num; i++)
array[i] = a[i];
}
bool operator== (const LNode l)const {
if (this->a != l.a || this->b != l.b || this->c != l.c)
return false;
int num = sizeof(this->array) / sizeof(this->array[0]);
for (int i = 0; i < num; i++)
if (array[i] != l.array[i])
return false;
return true;
}
二、通用数据类型类模板
这个部分主要实现一个常规的模板类,利用它实现链表的各种操作,主要的操作逻辑有
template <typename T>
class Element
{
public:
T data;
Element<T>* next;
Element(T Data) : data(Data) {}
~Element() {}
//按照索引查找
void FindDataByIndex(const Element<T>* head, const int num);
//按照元素内容查找
int FindDataByValue(const Element<T>* head, T value);
//查找与value相等的所有元素
void FindAllData(const Element<T>* head, T value);
//插入,默认尾插
Element<T>* InsertData(Element<T>* head, const T value);
//从指定位置插入
Element<T>* InsertData(Element<T>* head, const T value, int n);
//删除数据
Element<T>* DeleteData(Element<T>* head, int n);
//求表长
int Length(const Element<T>* head);
};
三、自定义结构体类型模板
这个部分主要是对于用户自定义的结构体数据类型,链表操作的实现
template <typename T>
class Element<LNode<T>>
{
public:
LNode<T> data;
Element<LNode<T>>* next;
Element(LNode<T> Data) { data.a = Data.a; data.b = Data.b; data.c = Data.c; data.array = Data.array; }
~Element() {}
//按照索引查找
void FindDataByIndex(const Element<LNode<T>>* head, const int num);
//按照给定value查找,value是结构体模板类型
int FindDataByValue(const Element<LNode<T>>* head, LNode<T> value);
//找到所有跟value相等的元素
void FindAllData(const Element<LNode<T>>* head, LNode<T> value);
//插入元素,默认尾插
Element<LNode<T>>* InsertData(Element<LNode<T>>* head, const LNode<T> value);
//从指定位置插入
Element<LNode<T>>* InsertData(Element<LNode<T>>* head, const LNode<T> value,int n);
//删除元素
Element<LNode<T>>* DeleteData(Element<LNode<T>>* head,int n);
//求表长
int Length(const Element<LNode<T>>* head);
};
四、实现代码
#include <iostream>
using namespace std;
template <typename U>
struct LNode {
int a;
double b;
char c