假设我有一个Sum方法来帮助递归地对链表中的元素求和,
void Sum(Node *head)
{
int sum = 0; //I think this is the problem since it resets the sum on each recursive call
while (head != NULL) {
Sum(head->next); //iterate to the last node before null
sum += head->data;
return;
}
cout << " The sum is : " << sum << endl;
}
我遇到的问题是我认为由于每次递归回拨我的总和值被重新初始化为0;所有递归完成后,允许我保持总和值的方法是什么?
答案 0 :(得分:2)
它可能比你拥有的要简单得多。我建议的改变:
while
循环和递归调用。使用其中一种。递归版:
int Sum(Node *head)
{
if ( head != NULL )
return head->data + Sum(head->next);
else
return 0;
}
循环版本:
int Sum(Node *head)
{
int sum = 0;
while (head != NULL) {
sum += head->data;
head = head->next;
}
return sum;
}
答案 1 :(得分:0)
(C代码)
对于上面的答案,循环版本不需要是:
int Sum(struct node* head)
{
int sum = 0;
while (head != NULL) {
sum += head->data;
head = head->next; // This needs to be added to go through all nodes
}
return sum;
}
另外,我相信你也可以这样做一个递归方法: (C代码)
int Sum(struct node* head)
{
if (head == NULL)
return 0;
return (head->data) + Sum(head->next);
}