为什么这个 C 链表会损坏?
我已经 2 年没有上过 CS 课了,我不明白为什么这个简单的链表会损坏:
int exists(linkedlist *list, int val) {
if(list == NULL)
return 0;
if(list->value == val)
return 1;
return exists(list->next, val);
}
当我尝试执行 exists(list,33);
时,列表的第一个值被覆盖33.我被迫使用迭代方法并使程序正常运行,但这让我感到烦恼,因为这似乎是一个有效的解决方案。为什么不起作用?
(注意:创建节点时我总是设置 list->next = NULL;
)
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;
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你确定第二个 if 语句是
而不是
这是我能看到的唯一会改变值的东西。
Are you sure the second if statement is
and not
That's the only thing I can see that would change the value.
究竟是什么不起作用?代码看起来完全没问题。
尝试在
valgrind
中运行您的程序,以检查您可能丢失的内存错误。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.