链表结点的删除

 注意:::free(p);free函数的使用范围必须是malloc()函数出来的内存空间才能够把这个垃圾内存给free掉。

链表结点的删除分为两种情况:头结点被删除导致头发生改变;其他结点被删除。

静态链表的结点删除:

  1 #include<stdio.h>
  2 
  3 struct test
  4 {
  5    int data;
  6    struct test *next;
  7 };
  8 
  9 void printLink(struct test *head)
 10 {
 11   struct test *point = head;
 12   while(point !=NULL ){
 13       printf("%d ",point->data);
 14       point = point->next;
 15   }
 16   putchar('\n');
 17 }
 18 struct test* deleteNode(struct test *head,int data)
 19 {
 20   struct test *point=head;
 21 
 22   if(head->data==data){
 23      head=head->next;
 24      return head;
 25   }
 26   while(point->next!=NULL){
 27      if(point->next->data==data){
 28         point->next=point->next->next;
 29         return head;
 30      }else{
 31         point=point->next;
 32      }
 33   }
 34   return head;
 35 }
 36 
 37 int main()
 38 {
 39   struct test *head=NULL;
 40   struct test t1 ={1,NULL};
 41   struct test t2 ={2,NULL};
 42   struct test t3 ={3,NULL};
 43   struct test t4 ={4,NULL};
 44   struct test t5 ={5,NULL};
 45 
 46   t1.next =&t2;
 47   t2.next =&t3;
 48   t3.next =&t4;
 49   t4.next =&t5;
 50 
 51   head=&t1;
 52   printLink(head);
 53   head=deleteNode(head,1);
 54   printLink(head);
 55 
 56   head=deleteNode(head,3);
 57   printLink(head);
 58   return 0;
 59 }
 60 

 动态链表结点删除

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 
  4 struct test
  5 {
  6    int data;
  7    struct test *next;
  8 };
  9 
 10 void printLink(struct test *head)
 11 {
 12   struct test *point = head;
 13   while(point !=NULL ){
 14       printf("%d ",point->data);
 15       point = point->next;
 16   }
 17   putchar('\n');
 18 }
 19 struct test* deleteNode(struct test *head,int data)
 20 {
 21   struct test *point=head;
 22 
 23   if(head->data==data){
 24      head=point->next;
 25      free(point);        //warning free()weizhi.
 26      return head;
 27   }
 28   while(point->next!=NULL){
 29      if(point->next->data==data){
 30         point->next=point->next->next;
 31         return head;
 32      }else{
 33         point=point->next;
 34      }
 35   }
 36   return head;
 37 }
 38 
 39 int main()
 40 {
 41   struct test *head=(struct test*)malloc(sizeof(struct test));
 42   head->data=1;
 43 
 44   struct test t2 ={2,NULL};
 45   struct test t3 ={3,NULL};
 46   struct test t4 ={4,NULL};
 47   struct test t5 ={5,NULL};
 48 
 49   head->next=&t2;
 50   t2.next =&t3;
 51   t3.next =&t4;
 52   t4.next =&t5;
 53 
 54   printLink(head);
 55   head=deleteNode(head,1);
 56   printLink(head);
 57 
 58   head=deleteNode(head,3);
 59   printLink(head);
 60   return 0;
 61 }
 62 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值