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

相关推荐
聆风吟º18 分钟前
【数据结构入门手札】数据结构基础:从数据到抽象数据类型
数据结构·数据类型·逻辑结构·数据对象·物理结构·数据项·数据元素
啊吧怪不啊吧20 分钟前
二分查找算法介绍及使用
数据结构·算法·leetcode
立志成为大牛的小牛2 小时前
数据结构——四十二、二叉排序树(王道408)
数据结构·笔记·程序人生·考研·算法
摇滚侠9 小时前
StreamAPI,取出list中的name属性,返回一个新list
数据结构·list
炸膛坦客11 小时前
FreeRTOS 学习:(十七)“外部中断”和“内核中断”的差异,引入 FreeRTOS 中断管理
stm32·freertos·实时操作系统
是苏浙13 小时前
零基础入门C语言之C语言实现数据结构之单链表经典算法
c语言·开发语言·数据结构·算法
橘颂TA13 小时前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
迷途之人不知返14 小时前
数据结构之,栈与队列
数据结构
MOONICK16 小时前
数据结构——哈希表
数据结构·哈希算法·散列表
FMRbpm18 小时前
链表5--------删除
数据结构·c++·算法·链表·新手入门