FreeRtos进阶——通用链表的实现方式

通用链表实现方式(一)

c 复制代码
struct node_t {
	struct node_t *next;
};

struct person {
    struct node_t node;
    char *name;
    int age;
};

struct dog {
    struct node_t node;
    char *name;
    int age;
    char *class;
};

在此链表中,node结构体被放在了最前面,因此当我们用node结构体存储不同类型(dog或者person)结构体信息时,node 结构体位置就是dog或者person结构体的位置。在想要使用dog或者person时,只需要使用强制类型转换的方法即可。

通用链表实现方式(二)

使用操作系统:Linux,RT-Thread

c 复制代码
struct person {
    char *name;
    int age;
    struct node_t node;
    char *address;
};

struct dog {
    char *name;
    int age;
    char *class;
    struct node_t node;    
};

在此链表中,node结构体的位置在最后面,因此我们需要根据person或者dog结构体的大小反推出他们的指针起始位置。

具体代码如下:

cpp 复制代码
p = (struct person *)((char *)pre - (unsigned int)&((struct person *)0)->node);
n = (struct person *)((char *)next - (unsigned int)&((struct person *)0)->node);

pre指针转换为char*后加减操作是以字节为单位了,否则是以sizeof(struct node_t)为单位来进行加减计算。

unsigned int类型的强制转换是因为要减去对应的字节数。

通用链表实现方式(三)

使用操作系统:FreeRtos

cpp 复制代码
struct node_t {
    void *container;
	struct node_t *next;
};

与前面俩种方法类似,如果直接在contianer存储person或者dog的结构体地址,那么就不需要再去计算或者反推对应结构体的地址了。

相关推荐
承渊政道23 分钟前
【优选算法】(实战体会位运算的逻辑思维)
数据结构·c++·笔记·学习·算法·leetcode·visual studio
承渊政道1 小时前
【优选算法】(实战推演模拟算法的蕴含深意)
数据结构·c++·笔记·学习·算法·leetcode·排序算法
历程里程碑3 小时前
Protobuf 环境搭建:Windows 与 Linux 系统安装教程
linux·运维·数据结构·windows·线性代数·算法·矩阵
代码探秘者3 小时前
【算法】吃透18种Java 算法快速读写模板
数据结构·数据库·python·算法·spring
WolfGang0073214 小时前
代码随想录算法训练营 Day21 | 回溯算法 part03
数据结构·算法
深邃-4 小时前
数据结构-队列
c语言·数据结构·c++·算法·html5
keep intensify4 小时前
二叉树的直径
数据结构·算法·深度优先
keep intensify5 小时前
单源最短路径
数据结构·c++·算法
篮l球场5 小时前
数组中的第K个最大元素
数据结构·算法·leetcode
月落归舟5 小时前
排序算法---(三)
数据结构·算法·排序算法