为什么这个C链表损坏了?

use*_*592 2 c recursion linked-list

我没有在2年内参加CS课我无法弄清楚为什么这个简单的链表正在腐败:

int exists(linkedlist *list, int val) {
    if(list == NULL)
        return 0;

    if(list->value == val)
        return 1;
    return exists(list->next, val);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试执行exists(list,33);时,列表的第一个值被33覆盖.我被迫使用迭代方法并使程序正常工作,但这会让我感到烦恼,因为这似乎是一个有效的解决方案.为什么不起作用?

(注意:创建节点时我总是设置list->next = NULL;)

BMi*_*tch 5

你确定第二个if语句是

if(list->value == val)
Run Code Online (Sandbox Code Playgroud)

并不是

if(list->value = val)
Run Code Online (Sandbox Code Playgroud)

这是我唯一能看到的会改变价值的东西.

  • 当你不打算修改参数时,使用`const`的一个很好的理由! (2认同)