问题
I have the following code:
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;
}
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?
回答1:
Change your loop to:
for (currentNode = list->head; currentNode !=NULL; currentNode = currentNode -> next) {
sum = sum + currentNode->data;
}
This will solve two problems:
- It will check that
list->head
is notNULL
; - It won't skip over the first element in the list when calculating the sum.
来源:https://stackoverflow.com/questions/28908852/returning-sum-of-values-in-linked-list