Why is this C linked list corrupting?
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;
)
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.
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.
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.
精彩评论