1

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");
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot! I see now where I was wrong in using the while statement. I was getting some things mixed up but this helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.