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

相关推荐
阿里巴巴P8资深技术专家3 小时前
Java常用算法&集合扩容机制分析
java·数据结构·算法
逸群不凡7 小时前
C++|哈希应用->布隆过滤器
开发语言·数据结构·c++·算法·哈希算法
HHFQ8 小时前
狄克斯特拉算法
数据结构·算法
0xCC说逆向11 小时前
数据结构 - C/C++ - 队列
数据结构
码界领航11 小时前
(6) 深入理解pandas的核心数据结构:DataFrame全面解析
数据结构·python·numpy·pandas
SplendidJie12 小时前
牛客链表题:BM1 反转链表(取头放尾法)
开发语言·c++·链表
danaaaa12 小时前
力扣刷题练习八【922. 按奇偶排序数组II】
数据结构·c++·算法·leetcode·职场和发展
青釉Oo12 小时前
数字流的秩
java·数据结构·算法·leetcode·二叉搜索树
小字节,大梦想13 小时前
C语言_练习题
c语言·开发语言·数据结构·后端·算法·leetcode
wcy20009713 小时前
代码随想录训练营Day56
数据结构·算法·leetcode