【发布时间】:2018-05-20 08:48:33
【问题描述】:
此代码来自this site.
void recursiveReverse(struct Node** head_ref)
{
struct Node* first;
struct Node* rest;
/* empty list */
if (*head_ref == NULL)
return;
/* suppose first = {1, 2, 3}, rest = {2, 3} */
first = *head_ref;
rest = first->next;
/* List has only one node */
if (rest == NULL)
return;
/* reverse the rest list and put the first element at the end */
recursiveReverse(&rest);
first->next->next = first;
/* tricky step -- see the diagram */
first->next = NULL;
/* fix the head pointer */
*head_ref = rest;
}
我不明白为什么在最后一次递归调用之后 rest 的值保持不变?我知道 recursiveReverse(&rest) 正在传递实际的 rest 地址,但这个地址不是仅由 head_ref 获取吗?这意味着每个递归调用都有自己的 first 和 rest 的本地副本,因此 *head_ref = rest 不应该工作,因为 rest 的值会不断变化。
我的理解哪里出了问题?
编辑:添加我的一些涂鸦。
【问题讨论】:
-
您似乎错过了
*head_ref = rest;在上一个循环(即您要返回的循环)中更改rest的值。所以通过这种方式,最后一个节点(你的 106)的地址传播到顶部并最终改变头指针 -
@4386427 我想我明白你在说什么。但我不明白为什么
*head_ref = rest;会在上一个循环中更改rest的值。为什么会发生这种情况? -
@momo 是递归的逻辑,在每次递归调用unitl hit base case时保存位置。击中后,回到你开始调用的地方(包括)
-
@momo 因为您传递了
&rest,所以head_ref是指向上一步的rest的指针,因此*head_ref = ...在上一步中更改了rest的值。跨度> -
@4386427 非常感谢,我现在看到了。
head_ref是指向rest的指针,这是我所缺少的。
标签: c pointers linked-list