Reputation: 51
I have not taken a CS class in 2 years I can not figure out why this simple linked list is corrupting:
int exists(linkedlist *list, int val) {
if(list == NULL)
return 0;
if(list->value == val)
return 1;
return exists(list->next, val);
}
When I try to execute exists(list,33);
the first value of the list is overwritten with 33. I was forced to use an iterative approach and got the program working, however this bugs me since this appears to be a valid solution. Why doesn't it work?
(NOTE: When creating nodes I always set list->next = NULL;
)
Upvotes: 2
Views: 130
Reputation: 263617
Are you sure the second if statement is
if(list->value == val)
and not
if(list->value = val)
That's the only thing I can see that would change the value.
Upvotes: 5
Reputation: 10350
By the way, how long is your linked list?
Probably not your problem here, but be aware that your recursive approach means you could end up with a stack overflow on very long lists.
Upvotes: 0
Reputation: 36433
What doesn't work exactly? The code looks perfectly OK.
Try running you program in valgrind
, to check for memory errors you might be missing.
Upvotes: 1