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?

  • 2
    Provide a minimal complete program that reproduces the problem. – Vlad from Moscow May 23 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 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 at 23:15
  • This code looks fine to me. Post a minimal reproducible example that can be run to show the incorrect sum, please. Since you're using floats, make sure you understand what to expect when summing them. – ggorlen May 24 at 0:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.