C 删除链接列表中的特定节点
需要搜索特定节点,然后删除,但由于某些原因,此代码不会最终更改需要删除的节点。cmdNum只是节点的位置,而不是结构中的值C 删除链接列表中的特定节点,c,C,需要搜索特定节点,然后删除,但由于某些原因,此代码不会最终更改需要删除的节点。cmdNum只是节点的位置,而不是结构中的值 CmdNode *deleteCommand(CmdNode *head, int cmdNum) { CmdNode *temp1 = NULL; CmdNode *temp2 = NULL; temp1 = head; temp2 = head -> next; int pos = 0;
CmdNode *deleteCommand(CmdNode *head, int cmdNum) {
CmdNode *temp1 = NULL;
CmdNode *temp2 = NULL;
temp1 = head;
temp2 = head -> next;
int pos = 0;
while (temp2!= NULL){
if(cmdNum == pos){
temp1 ->next = temp2->next;
free(temp2);
return head;
}
temp1 = temp1->next;
temp2 = temp2->next;
pos++;
}
return head;
}
对于初学者,temp2在一个只有1项的列表中被初始化为NULL 您没有考虑删除正在删除的列表(pos==0)的“head” 在head最初为null的情况下,您也不会考虑空列表。这肯定会在
temp2=head->next
时崩溃
以下是一些快速修复方法:
CmdNode *temp1 = NULL; // "previous"
CmdNode *temp2 = head; // "current"
int pos = 0;
while (temp2!= NULL){
if(cmdNum == pos){
if (temp1 != NULL) {
temp1->next = temp2->next; // previous now links to next
} else {
head = temp2->next; // head was deleted, new head
}
free(temp2);
return head;
}
// advance both pointers
temp1 = temp2;
temp2 = temp2->next;
pos++;
}
return head; // not found, just return the head of the unchanged list
此代码不解释空标头或是否要删除标头。需要查看哪些不起作用。它不能解释列表中只有一个项目并且该项目是要删除的项目。由于某些原因,它不起作用,它不会删除实际节点。你怎么知道?我的灵力建议你需要比较
cmdNum==temp2->value
或类似的内容,而不是cmdNum==位置
。这通常是在链表中搜索特定节点的方式。这里有代码向我们显示函数是否按预期工作,还有cmdNum dosen没有引用结构中的值,我怎么知道?说真的,让我们看看整个画面,而不仅仅是你认为缺陷所在的范围。