本文介绍了返回链表中的值之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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中所有值的总和.但是,我不断遇到细分错误.谁能帮助我发现致命错误?
I want it to return the sum of all the values in the linked list *list. However, I keep getting a segmentation fault. Can anyone help me spot the fatal error?
推荐答案
将循环更改为:
for (currentNode = list->head; currentNode !=NULL; currentNode = currentNode -> next) {
sum = sum + currentNode->data;
}
这将解决两个问题:
- 它将检查
list->head
不是NULL
; - 计算总和时,它不会跳过列表中的第一个元素.
- It will check that
list->head
is notNULL
; - It won't skip over the first element in the list when calculating the sum.
这篇关于返回链表中的值之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!