Recursion with linked list

I have a linked list I made and am practicing a simple recursion function sum() which returns the sum of all numbers in each node of the list.
I don't think the entire code is necessary or helpful but if I'm wrong I'll add that, here is my sum() function:

1
2
3
4
5
6
int sum(ListNode *ptr){
	if (ptr->next)
		return (ptr->num + sum(ptr->next));
	else
		return(0);
}


where the initial arg passed through the ListNode * parameter is my head node (with null value). The output is fine until that point, then the program locks up and I get the "...has stopped working" error. Any help is appreciated, Thanks for your time!
Last edited on
Have you initialised the tail node's next to null?

EDIT: Also, it appear that you are not adding the tail's number. change your else clause to:
return(ptr->num);
Last edited on
Topic archived. No new replies allowed.