返回链表中的值之和

时间:2015-03-06 22:36:13

标签: c++ pointers linked-list nodes

我有以下代码:

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;

}

我希望它返回链表*列表中所有值的总和。但是,我不断遇到分段错误。任何人都可以帮我发现致命错误吗?

1 个答案:

答案 0 :(得分:3)

将您的循环更改为:

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

这将解决两个问题:

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