gpt4 book ai didi

c - 递归 - 链表中倒数第 n 个元素

转载 作者:行者123 更新时间:2023-11-30 15:19:21 24 4
gpt4 key购买 nike

有人可以解释一下下面的函数吗?

void printNthFromLast(struct node* head, int n) 
{
static int i = 0;
if(head == NULL)
return;
printNthFromLast(head->next, n);
if(++i == n)
printf("%d", head->data);
}

我只是想知道递归中语句的执行顺序是如何发生的,即给定的递归调用是在第二个 if 条件之前,那么第二个 if 条件是否会被检查?

最佳答案

I just want to know how order of execution of statements occur in recursion i.e given recursive call is before the second if condition , so will the second if condition be checked ?

是的,在递归调用返回后,将检查第二个 if 条件。如果递归到达链表末尾而终止,它将返回。这个概念对于理解递归至关重要。最特别的是,您必须了解每个函数调用(包括递归函数调用)都在其自己的上下文中执行,并且在返回时控制在调用后立即恢复。它与执行流程相关,而不是与所调用的函数相关——您不会因为递归调用函数而失去自己的位置。

关于c - 递归 - 链表中倒数第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30721211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com