gpt4 book ai didi

c - 如何在C中更新全局链表?

转载 作者:行者123 更新时间:2023-11-30 14:34:18 25 4
gpt4 key购买 nike

我有一个名为 ACCOUNT 的结构,它有两个属性和一个指向下一个属性的指针。全局头由 NULL 启动。我想更新全局列表,但当我多次调用该函数时,头部仍然为 NULL。如何解决?


#include<string.h>
#include<stdio.h>
#include<stdlib.h>

struct ACCOUNT{
int accountNumber;
float balance;
struct ACCOUNT *next;
}
struct ACCOUNT *head = NULL ;


void findUpdate(int account, float amount){

struct ACCOUNT *current;
current = head;
while(current!=NULL){
if (current->accountNumber==account){
current->balance += amount;
}
current=current->next;
}
current = (struct ACCOUNT*) malloc(sizeof(struct ACCOUNT));
current->accountNumber = account;
current->balance = amount;
}

最佳答案

您需要将 findUpdate 末尾分配的新条目链接到列表中。我建议将 findUpdate 重写为:

void findUpdate(int account, float amount)
{
struct ACCOUNT *current;

for(current = head ; current != NULL ; current = current->next)
{
if(current->accountNumber == account)
{
current->balance += amount;
break;
}
}

if(current == NULL)
{
current = malloc(sizeof(struct ACCOUNT));
current->accountNumber = account;
current->balance = amount;
current->next = head;
head = current;
}
}

关于c - 如何在C中更新全局链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59020131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com