2014-12-06 86 views
0

我试着去理解下面的代码:传递指针地址在递归函数在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;  
} 

我注意到变量rest是具有用于所有的递归调用相同的值,一旦代码超越recursiveReverse(&rest)达到。但first->next有不同的值。我能够理解为什么first->next通过将它们写入堆栈并将它与每个调用进行比较而具有不同的值。但我无法理解rest对于所有呼叫的值是多少,而不是来自堆栈的(rest = first->next)。如果问题不清楚或需要任何细节,请告诉我。 感谢

更新:我注意到,妥善安排参数,如果我叫recursivereverse(休息),而不是rev​​ursivereverse(&休息),对于每一个递归调用就像revursion堆栈上的任何其他变量,其余值的变化。我不明白休息在通话中有什么不同&。

+1

执行'recursiveReverse(&rest);'''执行后,列表几乎相反,此时'rest'指向列表的最后一项,无论递归中的嵌套层次如何,它都是相同的 – 2014-12-06 06:51:07

回答

2

考虑以下输入。

首先递归,

*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。现在剩下的值改为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 

所以现在头_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在递归结束时进入最后位置。

+0

嗨,但在第二次递归调用中,我们在调用堆栈上,在递归之前我们有rest = first-> next。因此,休息应该有什么值,首先 - >下一个是正确的?..我观察到的另一件事是,如果我调用reverse(rest)而不是rev​​erse(&rest),那么程序不会以这种方式行为 – user1455116 2014-12-06 08:11:06

+0

在递归休息之前有你说的值。在递归中,我们传递其余的地址。另一件事,即使rest被改变,它的值,第一个指针指向位置不会改变。 – 2014-12-06 08:35:12

0

考虑一个链表1->2->3->4。根据recursiveReverse(),在(rest == NULL)满足(节点'4')时,在递归函数调用的迭代中,*head_ref = 4;现在在此之后,调用返回到先前的迭代(节点'3')。这里基本上rest(='4')函数递归当前迭代的变量(节点'3')实际上是最后一次迭代的*head_ref(最后一个节点'4'),其中*head_ref被计算为4.因此,在函数的末尾在递归(节点'3')中,我们正在做*head_ref = rest;,即。 *head_ref = 4,因为从函数迭代节点='4'接收rest作为4。现在在这些函数的下一个连续递归返回时,返回地址*head_ref,它保持相同,因此语句*head_ref = rest;给出了相同的值。