Returning sum of values in linked list

百般思念 提交于 2019-12-11 23:37:33

问题


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:

  1. It will check that list->head is not NULL;
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!