C语言 关于删除链表最后一个结点出错
以下是一个系统中的一个删除链表的函数,该函数有一个BUG就是在删除最后一个结点的时候会出错导致程序直接退出。
欢迎各位高手帮忙看看。
int
delete_student(student_list_t* listp,char target[]){
student_t* to_freep;
student_t* cur_nodep;
int is_deleted;
if(listp->size==0)/*If the list is empty,exit.*/
is_deleted=0;
else if(strcmp(listp->headp->student[0],target)==0){/*If the headp is the target,delete.*/
to_freep=listp->headp;
listp->headp=to_freep->restp;
free(to_freep);
--(listp->size);
is_deleted=1;
}else{
for(cur_nodep=listp->headp;
cur_nodep->restp!=NULL;
cur_nodep=cur_nodep->restp){
/*Current note's next note is the target and current note is not the last note.*/
if(cur_nodep->restp!=NULL && strcmp(cur_nodep->restp->student[0],target)==0){
to_freep=cur_nodep->restp;
cur_nodep->restp=to_freep->restp;
free(to_freep);
--(listp->size);
is_deleted=1;
}else
is_deleted=0;
}
}
return(is_deleted);
}
[解决办法]
for(cur_nodep=listp->headp;cur_nodep->restp!=NULL;) { if(cur_nodep->restp!=NULL && strcmp(cur_nodep->restp->student[0],target)==0) { to_freep=cur_nodep->restp; cur_nodep->restp=to_freep->restp; free(to_freep); --(listp->size); is_deleted=1; }
[解决办法]
原因出在for循环里
// 这里,如果循环到倒数第二个节点,满足条件,那么,该节点被删除(free), // 因为这条语句【cur_nodep->restp=to_freep->restp;】执行后, // cur_nodep指向最后一个节点,而因为用的是for循环,在循环最后 // 还将执行一遍【cur_nodep=cur_nodep->restp】语句,所以, // 此时的cur_nodep指向NULL,而回到循环头部再判断循环条件 // 【cur_nodep->restp!=NULL】时,因为cur_nodep已经是NULL了 // 所以,cur_nodep->restp这条语句出现问题,异常终了。 for(cur_nodep=listp->headp; cur_nodep->restp!=NULL; cur_nodep=cur_nodep->restp) { /*Current note's next note is the target and current note is not the last note.*/ if (cur_nodep->restp!=NULL && strcmp(cur_nodep->restp->student[0],target)==0) { to_freep=cur_nodep->restp; cur_nodep->restp=to_freep->restp; free(to_freep); --(listp->size); is_deleted=1; } else is_deleted=0; }
[解决办法]
答案如4楼。
其实一般在循环里查找某一个变量,如果查到了,请break退出。除非是多重目标。