c - 修改链接列表中的值 - 返回已编辑的列表,但缺少节点。 (C)

标签 c linked-list nodes

我的修改功能正在运行,但由于某种原因,当我打印出来时,列表中缺少一个节点。我想要编辑的节点已被编辑。我认为问题是当我应该将其分配为当前时,我以某种方式将 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;

此时,currenthead,因此mod 只是另一个指向head 的指针。在循环中你说:

mod->next = current;

由于 modhead,因此您将删除 headcurrent 之间的所有节点。因此,如果您尝试修改的节点位于列表的末尾,那么最终列表中将只有这 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/

相关文章:

c - 通过 C 套接字发送原始二进制数据?

CMake 不会创建目标文件并且无法链接

c - 我收到一个函数警告,但我不知道如何编写该函数,所以我不会再收到该警告

java - 从自定义列表中递归插入和删除

java - 如何在 java 中使用泛型类型的节点创建 get 方法

javascript - 在 javascript string.replace(from, to, index form) 中替换特定索引后的字符串

C - 如何为结构内的链表分配内存

c - 链表节点初始化,不使用malloc()

java - 迭代链表时出现 NullPointerException

python - (Python) Networkx - 如何为具有 pos 变量的节点设置自己的位置