13.3 链表-按顺序插入和查找删除节点

本文介绍了一个简单的链表数据结构实现,包括按顺序插入节点、按ID查找并删除节点的功能。通过示例展示了如何使用这些功能对链表进行操作。

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

13.3 链表-按顺序插入和查找删除节点


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Student
{
    int id;
    char name[16];
    Student* next;
};

// 定义了一个有头节点
Student m_head = {0};

// 按顺序插入节点
int insert(Student* obj)
{
    Student* cur = m_head.next; // 当前节点current
    Student* pre = &m_head;  // 上一个节点previous
    while(cur)
    {       
        if(obj->id < cur->id) // 找到这个位置
            break;

        pre = cur;
        cur = cur->next;  // 找到最后一个对象
    }

    // 插入到pre节点的后面
    obj->next = pre->next;
    pre->next = obj;
    return 0;
}

// 按id查找并删除节点
void remove(int id)
{
    Student* cur = m_head.next; // 当前节点current
    Student* pre = &m_head;  // 上一个节点previous
    while(cur)
    {       
        if(id == cur->id) // 找到这个位置
        {
            // 删除该节点
            pre->next = cur->next;
            free(cur);
            break;
        }
        pre = cur;
        cur = cur->next;  // 找到最后一个对象
    }
}

// 遍历
void show_all()
{
    Student* p = m_head.next; 
    while(p)
    {
        printf("ID: %d, name: %s\n", p->id, p->name);
        p = p->next; // 下一个对象
    }
}

int main()
{
    Student* obj = NULL;


    obj = (Student*)malloc (sizeof(Student));
    obj->id = 8;
    strcpy(obj->name, "888");
    insert(obj);

    obj = (Student*)malloc (sizeof(Student));
    obj->id = 1;
    strcpy(obj->name, "111");
    insert(obj);

    obj = (Student*)malloc (sizeof(Student));
    obj->id = 4;
    strcpy(obj->name, "444");
    insert(obj);

    obj = (Student*)malloc (sizeof(Student));
    obj->id = 3;
    strcpy(obj->name, "333");
    insert(obj);

    obj = (Student*)malloc (sizeof(Student));
    obj->id = 5;
    strcpy(obj->name, "555");
    insert(obj);

    remove(3);
    remove(2);
    show_all();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值