递归lnkedlist反向实现

时间:2014-07-05 11:37:01

标签: c recursion linked-list

//this is code...

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 */
    printf("\nbefore:%u,%d,%u,%d,%u,%d",*head_ref,               (*head_ref)->data,first,first->data,rest,rest->data);
    recursiveReverse(&rest);
    printf("\nafter:%u,%d,%u,%d,%u,%d",*head_ref,(*head_ref)->data,first,first->data,rest,rest->data);
    first->next->next  = first; 

    /* tricky step -- see the diagram */
    first->next  = NULL;         

    /* fix the head pointer */
    *head_ref = rest;      ///here is my doubt       
}

怀疑:此行如何以输出

中显示的方式影响堆栈内容

输出:

原始:10-> 12-> 14-> 16-> 18-> 20-> 22->

堆栈内容: 前:159592472,10,159592472,10,159592456,12 前:159592456,12,159592456,12,159592488,14 前:159592488,14,159592488,14,159592504,16 前:159592504,16,159592504,16,159592520,18 前:159592520,18,159592520,18,159592536,20 前:159592536,20,159592536,20,159592552,22 递归到达底部 之后:159592536,20,159592536,20,159592552,22 //为什么在解除引用休息时为每个堆栈打印22个

后:159592520,18,159592520,18,159592552,22 后:159592504,16,159592504,16,159592552,22 后:159592488,14,159592488,14,159592552,22 后:159592456,12,159592456,12,159592552,22 后:159592472,10,159592472,10,159592552,22 反转:22-> 20-> 18-> 16-> 14-> 12-> 10

谢谢你,如果你不理解我的问题,请发表评论

0 个答案:

没有答案