I am trying to print a linked list in reverse order using recursion. i.e. : if i added 1,2,3,4,5 to the linked list , the program should output 5,4,3,2,1. Here's the code:
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
};
void Print(struct Node* n)
{
if(n->next == NULL)
{
return;
}
Print(n->next);
printf("%d",n->data);
}
void Insert(struct Node** head_ref,int data)
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
if((*head_ref)==NULL)
{
(*head_ref) = new_node;
}
else
{
struct Node* temp = (*head_ref);
while(temp!=NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
}
int main()
{
struct Node* head = NULL;
Insert(&head,1);
Insert(&head,2);
Insert(&head,3);
Insert(&head,4);
Print(head);
}
I have also tried declaring the head pointer as a global variable but still is is not outputting anything. Any help would be appreciated. Also if you think there something missing in my code or something that i don't understand correctly, if possible please point me to some resources where i can learn the concept.
Thanks
CodePudding user response:
Two mistakes:
The loop condition int the loop that finds the last node is wrong.
It is:
while(temp!=NULL)
while it should be:
while(temp->next!=NULL)
Otherwise, the update at:
while (temp != NULL) { ... }
temp->next = new_node; // segmentation fault
will explode because temp
is NULL
at that place.
Second error:
When printing the early check if tail is reached should be:
if(n == NULL) // not `if (n->next == NULL)`
Otherwise, the tail will not be printed.
After those fixes the program prints:
1234
If you want to reverse the order just swap printf
and recursive Print()
calls:
Print(n->next);
printf("%d",n->data);