简体   繁体   中英

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 . 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. 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:

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. Remember, recursive algorithms need concrete exit strategies, and they're usually a simple if condition to do nothing and just exit the call

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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