C 为什么我不能从列表中删除节点?
每次我尝试这样做时,if语句中都会出现一个未经处理的异常?在这一点上,其他一切都很好C 为什么我不能从列表中删除节点?,c,struct,linked-list,unhandled-exception,C,Struct,Linked List,Unhandled Exception,每次我尝试这样做时,if语句中都会出现一个未经处理的异常?在这一点上,其他一切都很好 void DeleteEmp(struct node* head, int tempID){ struct node *curNode = head; struct node *prevNode = NULL; while (curNode != NULL) { if(curNode->empId
void DeleteEmp(struct node* head, int tempID){
struct node *curNode = head;
struct node *prevNode = NULL;
while (curNode != NULL) {
if(curNode->empId == tempID) { // error here
free(curNode);
printf("Employee %d removed from database", tempID);
}
prevNode = curNode;
curNode = curNode->next;
}
}
您正在使用
curNode
在释放它之后
while (curNode != NULL) {
if(curNode->empId == tempID) { // error here
free(curNode);
printf("Employee %d removed from database", tempID);
}
prevNode = curNode;
curNode = curNode->next; // PROBLEM HERE.
}
也许你的意思是在呼叫免费
后立即返回
void DeleteEmp(struct node* head, int tempID){
struct node *curNode = head;
struct node *prevNode = NULL;
while (curNode != NULL) {
if(curNode->empId == tempID) {
if ( prevNode == NULL )
{
// This means curNode is the head.
// Since curNode is about to be deleted,
// make the next node the head.
head = curNode->next;
}
else
{
// Since curNode is about to be deleted,
// change the next node of prevNode.
prevNode->next = curNode->next;
}
free(curNode);
printf("Employee %d removed from database", tempID);
return;
}
prevNode = curNode;
curNode = curNode->next;
}
}
释放节点之前,应将其从列表中删除
while (curNode != NULL) {
if(curNode->empId == tempID) {
if (prevNode){// remove the node from the list
prevNode->next = curNode->next;
}
else{
head = curNode->next;
}
free(curNode);
printf("Employee %d removed from database", tempID);
return;//assuming empId is unique return after you found it.
}
prevNode = curNode;
curNode = curNode->next;
}
在释放节点的位置,在释放节点之前,需要进行一些指针交换。
考虑这个
a->b->c->NULL
删除b应在释放前执行以下操作
a->c->NULL
请注意,特殊情况包括删除c、删除导致新头的a以及删除单例列表中唯一的节点
注意GList类型和handler函数在library GObject中。使用此列表代码而不是编写和调试此列表代码可能是有意义的 free
在未将节点从列表中删除的情况下删除节点是错误的