RT-Thread内核-单向链表

1、单向链表的结构体定义

/**
 * Single List structure 单链表结构体
 */
struct rt_slist_node
{
    struct rt_slist_node *next;             /**< point to next node. 指向下一个节点 */
};
typedef struct rt_slist_node rt_slist_t;    /**< Type for single list.单链表数据类型的重命名 */

2、单向链表的初始化

/**
 * @brief initialize a single list 初始化一个单链表
 *
 * @param l the single list to be initialized 参数l:需要被初始化的链表
 */
rt_inline void rt_slist_init(rt_slist_t *l)
{
    l->next = RT_NULL; /* 链表的下一个节点的指针为空指针 */
}
#define RT_SLIST_OBJECT_INIT(object) { RT_NULL }

3、在单链表尾部追加节点

/** 
 参数l:需要插入的单链表
 参数n:需要插入的新节点
*/
rt_inline void rt_slist_append(rt_slist_t *l, rt_slist_t *n)
{
    struct rt_slist_node *node;

    node = l;
    while (node->next) node = node->next; /* 定位到单链表 l 的尾部 */

    /* append the node to the tail 在尾部追加节点 n */
    node->next = n;
    n->next = RT_NULL;
}

4、单链表的插入

/**
函数作用:在 链表 l 后面插入 n
参数 l:需要插入的链表
参数 n: 插入的新节点
*/
rt_inline void rt_slist_insert(rt_slist_t *l, rt_slist_t *n)
{
    n->next = l->next;
    l->next = n;
}

5、获取单链表的长度

rt_inline unsigned int rt_slist_len(const rt_slist_t *l)
{
    unsigned int len = 0;
    const rt_slist_t *list = l->next;
    while (list != RT_NULL)
    {
        list = list->next;
        len ++;
    }

    return len;
}

6、从单链表中移除一个节点

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;/* 定位到节点 n */

    /* remove node */
    if (node->next != (rt_slist_t *)0) node->next = node->next->next;

    return l;
}

7、单链表的头


rt_inline rt_slist_t *rt_slist_first(rt_slist_t *l)
{
    return l->next;
}

8、单链表的尾

rt_inline rt_slist_t *rt_slist_tail(rt_slist_t *l)
{
    while (l->next) l = l->next; /* l 指向单链表尾部 */

    return l;
}

9、当前节点的下一个节点

rt_inline rt_slist_t *rt_slist_next(rt_slist_t *n)
{
    return n->next;
}

10、判断单链表是否为空

rt_inline int rt_slist_isempty(rt_slist_t *l)
{
    return l->next == RT_NULL;
}
发布了124 篇原创文章 · 获赞 21 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tyustli/article/details/103948478