#define rt_inline static __inline
1、双向链表的结构体定义
/** * Double List structure */ struct rt_list_node { struct rt_list_node *next; /**< point to next node.指向下一个节点 */ struct rt_list_node *prev; /**< point to prev node.指向上一个节点 */ }; typedef struct rt_list_node rt_list_t; /**< Type for lists. */
2、双向链表的初始化
/** * @brief initialize a list 初始化一个链表 * * @param l list to be initialized l:需要被初始化的链表 */ rt_inline void rt_list_init(rt_list_t *l) { l->next = l->prev = l; /*链表的下一个节点和上一个节点均指向自己*/ }
3、在一个链表后面插入一个节点/** * @brief insert a node after a list 在一个链表的后面插入一个链表 * * @param l list to insert it 原来需要被插入的链表 * @param n new node to be inserted 新插入的链表 * @attention 注意要先找到after链表 * l n after * | next-> | | next-> | | next-> | * | prev<- | | prev<- | | prev<- | * */ rt_inline void rt_list_insert_after(rt_list_t *l, rt_list_t *n) { l->next->prev = n; /*要插入链表的后一个节点的前一个节点的地址是新插入的链表的地址n*/ n->next = l->next; /*插入的节点的下一个节点的地址是上一个节点的下一个节点的地址*/ l->next = n; /*要插入节点的下一个节点的地址是n*/ n->prev = l; /*插入的节点的上一个节点的地址是上一个节点*/ }
4、在一个链表前面插入一个节点
/** * @brief insert a node before a list 在一个链表的前面插入一个链表 * * @param n new node to be inserted 原来需要被插入的链表 * @param l list to insert it 新插入的链表 * @attention 要先找到before链表 * * before n l * | next-> | | next-> | | next-> | * | prev<- | | prev<- | | prev<- | * */ rt_inline void rt_list_insert_before(rt_list_t *l, rt_list_t *n) { l->prev->next = n; /*要插入链表的前一个节点的后一个节点的地址是新插入的链表n*/ n->prev = l->prev; /*新链表的前一个节点的地址是要插入节点的上一个节点的地址*/ l->prev = n; /*要插入的节点的上一个节点地址是新的节点n*/ n->next = l; /*插入的节点的下一个节点地址是l*/ }
5、从链表中删除一个节点
/** * @brief remove node from list. 从链表中删除一个节点 * @param n the node to remove from the list. 需要被删除的节点 * @attention * * before n after * | next-> | | next-> | | next-> | * | prev<- | | prev<- | | prev<- | * */ rt_inline void rt_list_remove(rt_list_t *n) { n->next->prev = n->prev; n->prev->next = n->next; n->next = n->prev = n; }
6、测试链表是否为空
/** * @brief tests whether a list is empty 判断链表是否为空 * @param l the list to test. 需要被判断的链表 */ rt_inline int rt_list_isempty(const rt_list_t *l) { return l->next == l; /*链表的下一个节点地址是不是自己的地址 如果是自己的地址那么就是真 函数返回1 如果不是自己的地址那么就是假,函数返回0*/ }
7、获取链表长度/** * @brief get the list length 获取链表长度 * @param l the list to get. 需要获取的链表 */ rt_inline unsigned int rt_list_len(const rt_list_t *l) { unsigned int len = 0; const rt_list_t *p = l; while (p->next != l) { p = p->next; len ++; } return len; }
双向链表(一)--双向链表操作函数
最新推荐文章于 2024-04-10 15:29:40 发布