C语言链表实现实例

C语言链表实现实例

/*
******    链表测试函数
******    2024/05/24add
*/

/* 定义链表结构体 */
typedef struct student {
    char* name;          /* 学生姓名 */
    struct student *next; /* 指向下一个学生的指针 */
} student, *p_student;

p_student head = NULL; /* 初始化头部指针为NULL */

/* 实例化链表节点 */
student fyz = {"FYZ", NULL};  /* 创建学生 FYZ 节点 */
student dl = {"DL", NULL};    /* 创建学生 DL 节点 */
student fhx = {"FHX", NULL};  /* 创建学生 FHX 节点 */
student test = {"TEST", NULL};/* 创建学生 TEST 节点 */

/*
** 插入链表: 将新学生节点插入到链表末尾
** new_student: 要插入的学生节点
*/
void insert_list(p_student new_student)
{
    p_student last;

    if (head == NULL) /* 如果链表为空,直接插入新节点 */
    {
        head = new_student;
        new_student->next = NULL;
    }
    else
    {
        /* 查找链表的最后一个节点 */
        last = head;
        while (last)
        {
            if (last->next == NULL)
                break;
            else
                last = last->next;
        }

        /* 将新节点插入到链表末尾 */
        last->next = new_student;
        new_student->next = NULL;
    }
}

/*
** 移除链表中的指定节点
** old_student: 要移除的学生节点
*/
void remove_list(p_student old_student)
{
    p_student left_student; /* 定义要删除节点的前驱节点 */

    if (head == old_student) /* 如果要删除的节点是头节点 */
    {
        head = old_student->next;  /* 更新头节点为下一个节点 */
    }
    else
    {
        /* 查找要删除节点的前驱节点 */
        left_student = head;
        while (left_student)
        {
            if (left_student->next == old_student)
                break;
            else
                left_student = left_student->next;
        }

        if (left_student)
        {
            /* 跳过要删除的节点 */
            left_student->next = old_student->next;
        }
    }
}

/* 打印链表内容 */
void print_student(void)
{
    p_student tmp = head;

    while (tmp)
    {
        Debug_LOG("%s", tmp->name); /* 输出学生姓名 */
        tmp = tmp->next; /* 移动到下一个节点 */
    }
}

/*
 * 主函数示例
 */
int main(void)
{
    /* 插入节点到链表 */
    insert_list(&fyz);
    insert_list(&dl);
    insert_list(&test);
    insert_list(&fhx);

    /* 打印链表内容 */
    print_student();

    /* 移除链表中的 TEST 节点 */
    remove_list(&test);
    Debug_LOG("remove test!");

    /* 打印链表内容,验证移除操作 */
    print_student();
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值