[英]passing pointer address in a recursive function in c
我试图理解以下代码:
void recursiveReverse(struct node **head_ref)
{
struct node *first;
struct node *rest;
if (*head_ref == NULL)
return;
first = *head_ref;
rest = first->next;
if (rest == NULL)
return;
recursiveReverse(&rest);
first->next->next = first;
first->next = NULL;
*head_ref = rest;
}
我注意到,一旦代码超出了recursiveReverse(&rest)
,则变量rest
对于所有递归调用都具有相同的值。 但是first->next
具有不同的值。 通过将它们写入堆栈并将其与每个调用进行比较,我能够理解为什么first->next
具有不同的值。 但是我不明白rest
所有调用如何具有相同的值,而不是堆栈中的(rest = first->next)
。 如果问题不清楚或需要任何详细信息,请告诉我。 谢谢
更新:我观察到,如果我正确地排列了参数,那么如果我调用recursivereverse(rest)而不是revursivereverse(&rest),则每次递归调用的rest值都会改变,就像revsion堆栈上的任何其他变量一样。 我不明白&rest在通话中有什么区别。
考虑以下输入。
1 2 3 4。
第一次递归
*Head_ref = 1;//value of head_Ref
first =1; // first=*head_ref;
rest=2;// rest=first->next;
第二次递归
*Head_ref = 2;//value of head_Ref
first =2; // first=*head_ref;
rest=3;// rest=first->next;
第三递归。
*Head_ref = 3;//value of head_Ref
first =3; // first=*head_ref;
rest=4;// rest=first->next;
第四次递归
*Head_ref = 4;//value of head_Ref
first =4; // first=*head_ref;
rest=NULL;// rest=first->next;
条件失败,这是它调用的第三次递归。
第三递归
first=3;
first->next->next=first// here it means the rest link.
first->next=NULL;// it will make the pointer that is end.
*head_ref=rest; // making the starting address in this recursion
现在列表如下:4->3。rest的值更改为4。
现在到第二次递归,
其余的将指向4,但第一个->下一个将指向3。
first=2;
rest=4;
first->next->next=first// here it means the rest link.
first->next=NULL;// it will make the pointer that is end.
*head_ref=rest; // making the starting address in this recursion
因此,现在head_ref指向4。然后,列表将为4-> 3-> 2。
涉及到第一次递归,
这里,
first=1,rest=4, But first -> next =2.
first->next->next=first// here it means the rest link.
first->next=NULL;// it will make the pointer that is end.
*head_ref=rest; // making the starting address in this recursion
最终变成
4 -> 3 -> 2 -> 1.
因此,现在该列表被颠倒了。 在这里,最主要的是将*head_ref
放在递归结束时的最后位置。
考虑一个链表1->2->3->4
。 根据recursiveReverse()
,在满足(rest == NULL)
(节点'4')时,在递归函数调用的迭代中, *head_ref
= 4;此后,该调用返回到先前的迭代(节点'3' )。 这里,函数递归的当前迭代(节点“ 3”)的基本rest
(=“ 4”)变量实际上是最后迭代( *head_ref
最后节点“ 4”)的*head_ref
,其中*head_ref
计算为4,因此在递归函数(节点“ 3”),我们正在做*head_ref = rest;
,即。 *head_ref
= 4,因为从函数迭代节点='4'接收rest
的4。 现在在这些函数的下一个连续递归返回中,返回*head_ref
地址,该地址一直保持不变,因此语句*head_ref = rest;
给出相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.