此递归删除节点功能如何工作?

时间:2020-10-23 18:48:45

标签: c recursion

我对该功能的顺序有些困惑。它接受一个结构节点指针并释放每个节点,直到没有剩余节点为止(我认为)。我不明白的是,如果我们递归调用recursive_destroyer(),我不明白该函数将如何达到free(head)。与destroy_list()函数相同。调用递归函数不会重新启动该函数吗?这是代码:另外,Node和LinkedList是这里未包括的结构,仅供参考。

node *recursive_destroyer(node *head) // takes in node and deletes each node
{
  if (head == NULL) // if there are no nodes
    return NULL;

  recursive_destroyer(head->next); // cycle through each node
  free(head);

  return NULL;
}

LinkedList *destroy_list(LinkedList *list)
{
  if (list == NULL)
    return NULL;

  recursive_destroyer(list->head);
  free(list);

return NULL;
}

2 个答案:

答案 0 :(得分:0)

假设有3个节点:node_1 -> node_2 -> node_3序列看起来像这样

- recursive_destroyer(node_1)
- Not null, call recursive_destroyer(node_1->next (node_2))
  - Not null, call recursive_destroyer(node_2->next (node_3))
    - Not null, call recursive_destroyer(node_3->next (null))
       - null, return
    - free(node_3), return
  - free(node_2), return
- free(node_1), return

缩进显示递归级别。因此,如果两行具有相同的缩进,那么它们将出现在同一递归调用中。

答案 1 :(得分:0)

让我们举一个简短的例子

 int f()
 {
     return 100;
 }
 
 int main()
 {
     int x, y;

     x = f();
     return f();
     y = f();
 }

x = f(); 将在 f()完成后保存上下文,程序将执行下一个命令,即 return 命令。

返回命令之后的任何内容都不会执行。递归类似,完成子节点处理后,它将返回到当前节点。调用后没有返回命令,因此它将继续执行该功能,直到结束花括号为止。