简体   繁体   English

链表递归反向功能有问题

[英]Trouble with a linked list recursive reverse function

I am trying to print a linked list recursively. 我正在尝试递归打印链接列表。 I created my own helper function for a recursive print, and I call it in my main print reverse function. 我为递归打印创建了自己的帮助器函数,并在主打印反向函数中调用了它。

What happens is, my pointer to the head of the list will successfully go to the last element of the list, but it will crash. 发生的是,我指向列表开头的指针将成功转到列表的最后一个元素,但是它将崩溃。 I am not too sure on what exactly is happening here. 我不太确定这里到底发生了什么。 I have checked for out of bounds with my !=NULL . 我已经用我的!=NULL检查了范围。 I am sort of lost on why it is not printing it backwards after the pointer has been established at the last integer. 我迷失了为什么在最后一个整数处建立了指针之后它不向后打印的原因。 Here is my code. 这是我的代码。

void lst_recursion(NODE *p){
     while (p != NULL){
         lst_recursion(p->next);
         printf(FORMAT, p->val);
     }
}

void lst_print_rev(LIST *l) {
    NODE *p = l->front;
    printf("[");

    while (p!= NULL){
        lst_recursion(p);
    }
    printf("]\n");
}

First, you don't need a while loop in any of this. 首先,您无需在while进行任何 while循环。 The main entry point should look like this: 主要入口点应如下所示:

void lst_print_rev(const LIST *l) 
{
    printf("[");
    lst_recursion(l->front);
    printf("]\n");
}

And the actual function, assuming your list is null-terminated, should look simply like this: 假设您的列表以null终止,那么实际的函数应该看起来像这样:

void lst_recursion(const NODE *p)
{
    if (p == NULL)
        return;

    lst_recursion(p->next);
    printf(FORMAT, p->val);
}

This will recurse to the tail, do nothing on that value (NULL), then unwind back up the activation stack, reporting each node on the way out. 这将递归到尾部,对该值不做任何事情(NULL),然后展开后退激活堆栈,报告出路的每个节点。 Remember, recursive algorithms need concrete exit strategies, and they're usually a simple if condition to do nothing and just exit the call 请记住,递归算法需要具体的退出策略, if条件什么也不做,只是退出调用,它们通常是一个简单的条件

Best of luck. 祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM