gpt4 book ai didi

c++ - 返回链表中值的总和

转载 作者:行者123 更新时间:2023-11-28 00:18:15 28 4
gpt4 key购买 nike

我有以下代码:

int sum(LinkedList * list) {

assert(list!=NULL);

Node *currentNode = list->head;
int sum = 0;

for (currentNode = currentNode->next; currentNode !=NULL; currentNode = currentNode -> next) {
sum = sum + currentNode->data;

}
return sum;

}

我希望它返回链表 *list 中所有值的总和。但是,我不断遇到段错误。谁能帮我找出 fatal error ?

最佳答案

将循环更改为:

for (currentNode = list->head; currentNode !=NULL; currentNode = currentNode -> next) {
sum = sum + currentNode->data;
}

这将解决两个问题:

  1. 它将检查list->head 是否为NULL
  2. 计算总和时不会跳过列表中的第一个元素。

关于c++ - 返回链表中值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28908852/

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