【问题标题】:Recursive linked list reversal递归链表反转
【发布时间】: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


【解决方案1】:

我不明白为什么在最后一次递归调用之后 rest 的值 还是一样?

它遇到递归调用的基本情况并立即返回。

 /* List has only one node */
    if (rest == NULL)
       return;  

每个递归调用都有自己的 first 和 rest 的本地副本?

是的,没错。 See how it works.

*head_ref = rest 不应该工作,因为 rest 的值会不断变化。

没有。它最终指向链表的最后一个元素,这将是第一个元素,我的意思是最右边的节点(在未更改的列表中)将被指向。

【讨论】:

  • 谢谢!我仍然对您回答的第三点感到困惑。在达到基本情况后,*head_ref = 106(根据我的假设)。现在当它回到调用函数时,这个函数中rest的值不是104,这会使*head_ref = 104等等?
  • 认为列表由102->104->106->NULL组成,*head_ref指向102,在下一个递归调用中指向104在下一个电话106不是 NULL 因为它已经被退回,这要归功于基本情况。最终 *head_ref 是指向 106 @momo 的指针
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-22
  • 2016-09-26
  • 2012-11-05
  • 2020-10-02
  • 2018-11-16
  • 1970-01-01
相关资源
最近更新 更多