RT-Thread ------ 链表的操作(不同于常规链表操作)
RT-Thread中的链表指针定义为rt_list_t或者rt_slist_t,而不是节点类型作为指针,这就可以使链表的操作(例如:插入、删除)不用和节点类型绑定,使得一套插入删除函数可以被各种节点类型使用,甚至可以将不同类型的节点插入链表。

使用举例: //定义单向链表结构体类型 struct rt_slist_node { struct rt_slist_node *next; }; typedef struct rt_slist_node rt_slist_t; //定义一个全局的链表变量 static rt_slist_t at_device_list = {0}; //链表初始化 rt_inline void rt_slist_init(rt_slist_t *l) { l->next = RT_NULL; } //定义节点类型 struct at_device { char name[RT_NAME_MAX]; /* AT device name */ rt_bool_t is_init; /* AT device initialization completed */ struct at_device_class *class; /* AT device class object */ struct at_client *client; /* AT Client object for AT device */ struct netdev *netdev; /* Network interface device for AT device */ rt_slist_t list; /* AT device list */ void *user_data; /* User-specific data */ }; //链表尾添加节点 void list_append(struct at_device *device) { rt_slist_init(&(device->list)); rt_slist_append(&at_device_list, &(device->list)); } rt_inline void rt_slist_append(rt_slist_t *l, rt_slist_t *n) { rt_slist_t *node; node = l; while (node->next) node = node->next; /* append the node to the tail */ node->next = n; n->next = RT_NULL; } //遍历链表 void list_foreach() { rt_slist_t *node = RT_NULL; struct at_device *device = RT_NULL; rt_slist_for_each(node, &at_device_list) { device = rt_slist_entry(node, struct at_device, list); } } #define rt_slist_for_each(pos, head) \ for (pos = (head)->next; pos != RT_NULL; pos = pos->next) #define rt_slist_entry(node, type, member) \ rt_container_of(node, type, member) #define rt_container_of(ptr, type, member) \ ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member))) //移除指定节点 rt_inline rt_slist_t *rt_slist_remove(rt_slist_t *l, rt_slist_t *n) { /* remove slist head */ struct rt_slist_node *node = l; while (node->next && node->next != n) node = node->next; /* remove node */ if (node->next != (rt_slist_t *)0) node->next = node->next->next; return l; }

浙公网安备 33010602011771号