单向链表(一)--单向链表操作函数

本文详细介绍了单链表的基本操作,包括结构体定义、初始化、追加和插入节点、获取长度、移除节点等核心功能,并提供了每个操作的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tyustli

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值