I'm practicing with linked lists using C. I'm a beginner programmer just started learning C two weeks ago.
I understand the concept of linked list very well and I was trying to reverse a linked list using recursion.
I know how to reverse it using a while loop, however with the recursion I'm stuck on how to point the head pointer to the last number address instead of the initial first number address after I reverse the list.
Below is my reverse function. The head is defined in main and I'm calling it by reference into my function. I know I can solve the issue by calling it by value and just writing in main() head=reverse(node* head); or by defining head in the dynamic memory and just accessing it straight from the function. I don't want to do that. I want to call it by reference from main and the function to return void.
Here is my reverse function:
void reverse(struct node** head)
{
struct node* p=*head;
if(p->link==NULL)
{ *head=p;
return;
}
reverse(&(p->link));
p->link->link=p;
p->link=NULL;
}
Say The list is: 5 6 7 2 3 4 The output I'm getting after reverse is: 5 I know the reason is because the head is still pointing at the first number address. I cant figure it out how to point it to the last number address. It should have done that in the if statement when it breaks the recursion function. But its not working.
Thank you!