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



我的修改函数正在工作,但由于某种原因,当我打印它时,列表中缺少一个节点。不过,我要编辑的节点已被编辑。我想问题是,当我应该将mod->next分配给current->next时,我会以某种方式将其分配给current。我解决不了。我已经尝试不同的组合有一段时间了。感谢的帮助

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 payn",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 payn",modID);
                head = mod;
                return;
            }
            current = current -> next;
            mod -> next = current;
        }
    }
}

mod只分配给一次:

mod = current;

在这一点上,current就是head,所以mod只是指向头部的另一个指针。在循环中,你说:

mod->next = current;

由于modhead,因此删除了headcurrent之间的所有节点。因此,如果您试图修改的节点位于列表的末尾,那么您最终只会看到列表中的这两个节点。

删除不需要的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 payn",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 payn",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 payn",modID);
        return;
    }
    current = current -> next;
}

这是在链表中循环的常用方法。

node* current = head;
while( current != NULL )
{
    // do stuff with current
    current = current->next;
}

如果你想更改函数接收modID的节点的工资,那么这个代码就足够了

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; (not needed)
            printf("nPerson with ID %d has a new payn",modID);
            return;
    }
    //mod = current; (not needed)   
    // Otherwise, loop for value
    while (current != NULL){
        if (current->ID == modID){
            current->sal = modsal;
            printf("nPerson with ID %d has a new payn",modID);
            //head = mod; (not needed)
            return;
        }
        current = current -> next;
        //mod -> next = current; (not needed)
    }
}

}

相关内容

  • 没有找到相关文章

最新更新