Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linked List Recursive Value Sum

I am trying to recursively determine the sum of the values in a linked list.

I am aware of one recursive solution that works:

def sum_list_rec1(head_node: Node):
   if head_node == None:
       return 0

   return head_node.value + sum_list_rec1(head_node.next)

However, I am trying to use the pattern where a variable is passed to the recursive function initially which will store the total sum.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the code:

def sum_list_rec2(head_node: Node):
   val_sum = 0
   calc_sum_rec(head_node, val_sum)
   return val_sum

def calc_sum_rec(head_node: Node, val_sum: int):
   if head_node == None:
      return

   val_sum += head_node.value
   calc_sum_rec(head_node.next, val_sum)

If I try to print out the output of the sum_list_rec2() function with a linked list (e.g. (1) -> (2) -> (3) -> (4)), I get an output of 0.

>Solution :

You can make your second snippet work by returning the new value:

def sum_list_rec2(head_node: Node):
   return calc_sum_rec(head_node, 0)

def calc_sum_rec(head_node: Node, val_sum: int):
   if head_node == None:
      return val_sum

   val_sum += head_node.value
   return calc_sum_rec(head_node.next, val_sum)

Actually the second function is better like this:

def calc_sum_rec(head_node: Node, val_sum: int):
   if head_node == None:
      return val_sum

   return calc_sum_rec(head_node.next, val_sum + head_node.value)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading