Program to reverse a linked list using recursion

I generally find Complex and confusing code on internet of reversing a linked list.So this is the simplest code of reversing a linked list using recursion.

Algorithm :-

1)we will take the head node as first node and rest all nodes as rest node and recursively call the rest node again.

2)when we get the first node and rest node in the last call of recursion.we will make following

first_node->next->next=first_node /* first next of next will be pointing to the first node */
first_node->next=NULL /*first next will be null.Thus we have reversed first and rest node */

3) Finally when all the recursion call is over we will have reversed linked list.

Program :-

Its just a function of reversing a linked list

void Reverselinkedlist (struct node **head)
{
struct node *first_node;
struct node *rest_node;
if(*head==NULL)
return 0;
first_node=*head;
rest_node=first_node->next;
if(rest_node==NULL)
return 0;
Reverselinkedlist(&rest_node);
first_node->next->next=first_node;
first_node->next=NULL;
*head=rest_node;
}


Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced