c - 在 C 中使用递归反转链表

标签 c linux

我正在尝试使用递归反转链表。我在 geeksforgeeks 网站上查看了示例程序。他们玩得很开心explanation 。但我无法理解 *headref 在每次堆栈展开时将保留什么。它不是在每次堆栈展开期间保存下一个地址吗?如果是这样,那么在所有堆栈展开调用期间剩余值如何相同。第一个值在堆栈展开期间发生更改,其余值也是如此。当每次堆栈展开更改第一个值时,为什么剩余值没有更改。请帮忙理解。

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 指向的第一个项目就成为其最后一个项目,因此之前的“第一个”将被附加到之后那个。那么它是最后一项,因此它的 next 成员变为 NULL。最后我们通过call参数返回新的head。

关于c - 在 C 中使用递归反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28480769/

相关文章:

c - 如何在 Linux 中获取 C/C++ 中的内存访问类型

C 自由() : invalid pointer allocated in other function

c - AVR:C 微 Controller 中的设置位

c - 这将更快地编译和/或计算斐波那契数列的前 100 个数字 : C or Brainfuck

linux - 免root安装TCL/TK

c - 在 pthreads 原始套接字中接收数据包

C - 抛出异常 : read access violation

Objective-C C 风格函数

linux - 按 cron 计划删除文件

linux - 在几分钟内解析/格式化 ps -eo etime?