链表的插入和删除

struct LNode
{
    int32_t data;
    struct LNode *next;
};
//初始化一个带头节点的单链表,指针L指向头节点
struct LNode *list_init(void)
{
    struct LNode *L = (struct LNode *)malloc(sizeof(struct LNode));
    if(L == NULL){
        printf("[list_init]malloc error\n");
        return NULL;
    }
    L->data = 0;
    L->next = NULL;
    return L;
}
//从链表末尾添加节点
int32_t list_add_element(struct LNode *L, int32_t element)
{
    if(L == NULL){
        printf("[list_add]list head is NULL\n");
        return -1;
    }
    struct LNode *add_node = (struct LNode *)malloc(sizeof(struct LNode));
    if(add_node == NULL){
        printf("[list_add]malloc error\n");
        return -1;
    }
    add_node->data = element;
    add_node->next = NULL;

    struct LNode *p = L;
    while(p->next != NULL) //找到末尾节点
    {
        p = p->next;
    }
    p->next = add_node;
    L->data++; 
    return 0;
}
//删除第几个节点
int32_t list_delete_element(struct LNode *L, uint32_t index)
{
    if(L == NULL){
        printf("[list_add]list head is NULL\n");
        return -1;
    }
    if(L->data < index){
        printf("Number of nodes is insufficient\n");
        return -1;
    }

    struct LNode *p = L;
    while(--index)
    {
        p = p->next;
    }
    struct LNode *del_node = p->next;
    p->next = p->next->next;
    L->data--;
    free(del_node);
    return 0;
}
uint32_t list_get_element_size(struct LNode *L)
{
    if(L == NULL){
        printf("[list_add]list head is NULL\n");
        return -1;
    }
    return L->data;
}
//测试代码
static struct LNode *list = NULL;
void main()
{
    list = list_init();
    list_add_element(list, 1);
    list_add_element(list, 2);
    list_add_element(list, 3);
    list_add_element(list, 4);
    list_add_element(list, 5);
    printf("%d\n", list->data);
    list_delete_element(list, 1);
    printf("%d\n", list->next->data);
    list_delete_element(list, 2);
    printf("%d\n", list->next->data);
    printf("%d\n", list->next->next->data);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

吴子坤

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

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

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

打赏作者

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

抵扣说明:

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

余额充值