寒假每日总结

本文详细介绍了链表数据结构中删除元素和插入元素的方法,包括无头节点和有头节点情况下头插法、尾插法的示例,以及如何处理特殊情况如删除头节点和更新头节点计数。
摘要由CSDN通过智能技术生成

链表

删除元素:


    struct no  *shead; //设置虚拟头节点方便进行代码的添加与删除操作
    shead = (struct no *)malloc(sizeof(struct no));
    shead->next = head;
   struct no *cur = shead;
    while(cur->next != NULL){
        if (cur->next->val == val){
            struct no *tmp = cur->next; // tmp指针指向所需删除的元素空间
            cur->next = cur->next->next;

// 将cur指向的元素中的next重新指向cur下下个元素(cur下个元素即所需删除的元素)
            free(tmp); // 释放需要删除的元素空间
        }
        else{
            cur = cur->next; // cur指向下一个元素
        }
    }
    head = shead->next; / / 头指针重新指向防止之前的循环删除了头元素的情况
    free(shead); / / 释放虚拟指针

元素插入


struct no{

         int data;

          struct no *next;

}*head;

头插法:


不带头节点:
  struct no *cur =(struct no *)malloc(sizeof(struct no));

cur->data=a;

cur->next=head;

head=cur;

带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));

cur->data=a;

cur->next=head->next;

head->next=cur;

尾插法:


不带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));

cur->data=a;

cur->next=NULL; // 由于是尾插法,结尾元素的next指向一定为NULL

if(head==NULL){

    head=cur;

}else {

  struct no *last =head;

while(last->next!=NULL){

        last=last->next;

}

last->next=cur;

}

带头节点:
struct no *cur =(struct no *)malloc(sizeof(struct no));

cur->data=a;

cur->next=NULL; // 由于是尾插法,结尾元素的next指向一定为NULL

struct no *last =head;

while(last->next!=NULL){

        last=last->next;

}

last->next=cur;

head->data=head->data+1;//此句是利用头节点中1的data来记录该链表的有效元素数量

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值