1

I have two functions that finds sum of a very huge linked list.And recursive one does not give the true answer. (I have given the actual sum. So I know if the output is true or not)

My code:

float sum_linkedlist(numlist *head) {
  if(head!=NULL)
    return sum_linkedlist(head->next) + head->data;
  else
    return 0;
}

I cannot find what is wrong with my code.Can somebody help me?

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    Provide a minimal complete program that reproduces the problem. – Vlad from Moscow May 23 '20 at 22:58
  • It would be a lot easier to explore its correctness with a short linked list. With a huge one there is the very real possibilty that a recursive solution will cause stack overflow. – Weather Vane May 23 '20 at 23:02
  • What is the expected and actual sum? How many elements in that list? Iterative solution in single function might have higher accuracy than float. – Piotr Praszmo May 23 '20 at 23:15
  • This code looks fine to me. Post a [mcve] that can be run to show the incorrect sum, please. Since you're using floats, make sure you understand [what to expect](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) when summing them. – ggorlen May 24 '20 at 00:30

0 Answers0