Tuesday, July 12, 2011

Simple C Program to reverse Singly LinkedList using recursion

Code:

void reverse(struct node** headRef) 
{
     struct node* first;
     struct node* rest;
     if (*headRef == NULL) 

            return;
     first = *headRef;
     rest = first->next;
     if (rest == NULL) return;
     reverse(&rest);
     first->next->next = first;
     first->next = NULL;
    *headRef = rest;
  }

2 comments:

Anonymous said...

Perhaps you may like this too:

static Node ReverseLinkedListRecursively(Node node, Node next)
{
if(node == null)
return null;

if (node.Next == null)
{
node.Next = next;
return node;
}

Node tempNext = node.Next;
node.Next = next;
return ReverseLinkedListRecursively(tempNext, node);
}

Invoke this as such: ReverseLinkedListRecursively(head, null);

Dhinakaran said...

Thank u for ur comment . your code looks great and easy to understand .