我的修改功能正在运行,但由于某种原因,当我打印出来时,列表中缺少一个节点。我想要编辑的节点已被编辑。我认为问题是当我应该将其分配为当前时,我以某种方式将 mod->next 分配给 current -> next 。我无法解决它。一段时间以来一直在尝试不同的组合。感谢您的帮助
void modify(int modID,double modsal){
type *current;
type *mod;
current = head;
if (current != NULL)
{
// if first node
if (current->ID == modID){
current->sal = modsal;
head = current;
printf("\nPerson with ID %d has a new pay\n",modID);
return;
}
mod = current;
// Otherwise, loop for value
while (current->next != NULL){
if (current->ID == modID){
current->sal = modsal;
printf("\nPerson with ID %d has a new pay\n",modID);
head = mod;
return;
}
current = current -> next;
mod -> next = current;
}
}
}
最佳答案
mod
仅分配给一次:
mod = current;
此时,current
是head
,因此mod
只是另一个指向head 的指针。在循环中你说:
mod->next = current;
由于 mod
是 head
,因此您将删除 head
和 current
之间的所有节点。因此,如果您尝试修改的节点位于列表的末尾,那么最终列表中将只有这 2 个节点。
删除不需要的mod
:
type *current;
current = head;
if (current != NULL)
{
// if first node
if (current->ID == modID){
current->sal = modsal;
printf("\nPerson with ID %d has a new pay\n",modID);
return;
}
// Otherwise, loop for value
while (current->next != NULL){
if (current->ID == modID){
current->sal = modsal;
printf("\nPerson with ID %d has a new pay\n",modID);
return;
}
current = current -> next;
}
}
此外,您不想重新分配head
,因为这会更改列表。由于您将其与自身重新分配,它碰巧起作用了,因此它没有改变。
编辑注意到另一个错误
您的 while
循环正在检查下一个值是否为空,因此您永远不会检查列表中的最后一个值。您可以稍微折叠代码并消除此问题:
type *current;
current = head;
while(current != NULL)
{
if (current->ID == modID){
current->sal = modsal;
printf("\nPerson with ID %d has a new pay\n",modID);
return;
}
current = current -> next;
}
这是循环链接列表的常用方法。
node* current = head;
while( current != NULL )
{
// do stuff with current
current = current->next;
}
关于c - 修改链接列表中的值 - 返回已编辑的列表,但缺少节点。 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26023302/