c++模板类链表(模板结构体,模板类,运算符重载)

一、存放数据的结构体

首先需要自定义一个存放数据的结构体模板,假定结构体中需要存放的数据类型有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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值