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

相关推荐
chlk12315 小时前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
张小潇3 天前
AOSP15 Input专题InputManager源码分析
android·操作系统
何中应4 天前
vi编辑器使用
linux·后端·操作系统
何中应4 天前
Linux进程无法被kill
linux·后端·操作系统
何中应4 天前
rm-rf /命令操作介绍
linux·后端·操作系统
何中应4 天前
Linux常用命令
linux·操作系统
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245034 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA4 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法