Hi All
I was trying to reverse a linklist in reverse direction using the recursion. I was able to reverse n - 1 element but it is not printing the first one. Below is my code.
Code:
typedef struct linklist
{
int data;
linklist *next;
};
void add(int data,linklist **node)
{
linklist *temp,*temp2;
temp = (struct linklist *) malloc(sizeof(linklist));
temp->data = data;
temp->next = NULL;
if (*node == NULL )
{
*node = temp;
return;
}
temp2 = *node;
while ( temp2->next != NULL )
temp2 = temp2->next;
temp2->next = temp;
}
void reverse_recur(linklist *node)
{
if (node != NULL )
{
node = node->next;
reverse_recur(node);
if ( node != NULL)
printf("\n Print In Reverse Order\n %d\n",node->data);
}
}
int main()
{
linklist *node = NULL;
add(1,&node);
add(2,&node);
add(3,&node);
add(4,&node);
print(&node);
reverse_recur(node);
This is happening since recursion is starting from second node, which is due to reason not printing the first one when recursion print values from stack once
Condition is met.
Do anybody help to print the first node too.
Currently I am using below statement for printing the first element;
reverse_recur(node);
printf("\n Print In Reverse Order\n %d\n",node->data);
But this I don;t want. Any body has idea on this.
Thanks