Reverse a singly linked list

Write the code to reverse a singly linked list, using recursion.

Answer:

Node* __reverse(Node *n, Node *next)
{
if (!n) return NULL;
if (!next) return n;
Node *tmp = next->next;
next->next = n;
return __reverse(next, tmp);

}

Node* ReverseLinkedList(Node* head)
{
if (!head) return NULL;
Node *rev_head = __reverse( head, head->next );
head->next = NULL;
return rev_head;
}

No comments: