为了账号安全,请及时绑定邮箱和手机立即绑定

C语言链表问题,为何就读进去一个数,del函数个人觉得没什么错误,求指点!

C语言链表问题,为何就读进去一个数,del函数个人觉得没什么错误,求指点!

C
onetwosix 2016-03-17 11:20:56
#include <stdio.h>#include <stdlib.h>struct number{ int shu; struct number *next;};struct number *create(int length){ struct number *head; struct number *p1,*p2; int i; p1=p2=(struct number *)malloc(sizeof(struct number)); p1->shu=1; head=p1; for(i=2;i<=length;i++) { p1=(struct number *)malloc(sizeof(struct number)); p1->shu=i; p2->next=p1; p2=p1; } p1->next=NULL; return (head); }struct number *del_3(struct number *head,int length){ struct number *p,*temp; int count=2; p=head; while(length>1) { if(count%3==0) { count=1; temp=p->next; p->next=temp->next; free(temp); p=p->next; length--; } else  p=p->next; count++; } return (p);}void print(struct number *p){ printf("%d\n",p->shu);}int main(){ int length ; struct number *head,*p; printf("input length: "); scanf("%d",&length); head=create(length); p=del_3(head,length); print(p); return 0;}
查看完整描述

1 回答

?
onemoo

TA贡献883条经验 获得超454个赞

在del_3中,你用temp和p依次指向后面的元素,但你没有注意判断是否临近最后一个元素。

如果p已经指向了最后一个元素,那么temp = p->next就是NULL,随后再 temp->next 试图访问NULL会发生segmentation fault。

while中的length并没有能够很好地判断剩余元素的个数,因为在if的else分支中,p仍然前进了,但length没有做相应的变化。

查看完整回答
反对 回复 2016-03-17
  • 1 回答
  • 0 关注
  • 1394 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信