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的结构体地址,那么就不需要再去计算或者反推对应结构体的地址了。

相关推荐
_x_w1 小时前
【12】数据结构之基于线性表的排序算法
开发语言·数据结构·笔记·python·算法·链表·排序算法
爱编码的傅同学1 小时前
数据结构(五)——AVL树(平衡二叉搜索树)
数据结构·算法
Bonnie_12151 小时前
02-redis-数据结构实现原理
数据结构·redis·算法
折枝寄北2 小时前
数据结构 | 证明链表环结构是否存在
数据结构·链表
LAOLONG-C2 小时前
先占个日常,等会写。
数据结构
_Vinyoo3 小时前
算法——分治
数据结构·算法
Dovis(誓平步青云)3 小时前
【数据结构】排序算法(下篇·终结)·解析数据难点
c语言·数据结构·学习·算法·排序算法·学习方法·推荐算法
愚润求学5 小时前
【C++】list模拟实现
开发语言·数据结构·c++·list
hxung8 小时前
B+树与红黑树
数据结构·b树
龙俊杰的读书笔记9 小时前
[leetcode] 面试经典 150 题——篇9:二叉树(番外:二叉树的遍历方式)
数据结构·算法·leetcode·面试