运行中会出现段错误,这是我的代码
Pstu DeleteNode(char * name) │
{ │
Pstu Pn = Phead; │
Pstu Pm = Pn; │
int flag = 1; │
│
if(Pn == Pend) │
{ │
│
if(Pn == NULL) │
{ │
printf("you need to add some student first!"); │
return NULL; │
} │
else if(!strcmp(Pn->name,Pn->name)) │
{ │
printf("only1 and get it!"); │
│
return Pn; │
} │
} │
else if(Pn->next == Pend) │
free(Pn); │
else │
{ │
while(Pn != Pend ) │
{ │
if(!strcmp(Pn->name,name)) │
{ │
if(flag == 1) │
{ free(Pn); │
break; │
} │
else │
{ │
free(Pn); │
Pn = Pn->next; │
Pm->next = Pn; │
printf("infindwhile get it"); │
return Pm; │
} │
│
} │
else if(flag == 0)
{ │
Pm = Pn; │
Pn = Pn->next; │
Pm->next = Pn; │
} │
else │
{ │
flag = 0; │
Pn = Pn->next; │
│
Pm->next = Pn; │
} │
} │
if(!strcmp(Pn->name,name)) │
{ │
free(Pn); │
printf("finally delete it"); │
printf("%d\n",Pn->score); │
return Pm; │
} │
else │
printf("no one\n"); │
}
答案 0 :(得分:1)
Appart的事实是您的实现仅对于节点删除功能来说就显得太大了(大约需要10行),这里是您应该关注的一些建议: -永远不要像在这里一样释放内存后再使用内存
else
{
free(Pn);
Pn = Pn->next;
Pm->next = Pn;
printf("infindwhile get it");
return Pm;
}
始终检查所有代码路径的返回值。在某些情况下,您的函数不会返回任何内容。
命名变量时要更清楚。 (在Pm和Pn之间,我真的不知道您的意思,有时甚至感觉您都不知道了)
精确地将所需的内容作为函数的返回值,因为根据我们检查函数的哪一部分,甚至返回值也不清楚。
PS:非常抱歉,您没有在评论中发布此内容,但我仍然缺乏4声望:'(