Reverse of a singly linked list using recursion

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
int data;
struct Node *next;
}Node;

typedef Node *list;

list reverse(list l)
{
if(!l || !l->next)
return l;

list ret = reverse(l->next);

l->next->next = l;

l->next = NULL;

return ret;

}

list insert(list l, int n)
{
Node *node = calloc(1, sizeof(Node));
node->data = n;

node->next = l;

return node;
}
void print(list l)
{
while(l)
{
printf("%d ", l->data);
l = l->next;
}

printf("\n");
}




int main()
{
int n, i;

scanf("%d", &n);

list l = NULL;
for(i = 0; i < n; i++)
l = insert(l, i);

printf("Before reverse:\n");
print(l);

l = reverse(l);

printf("After reverse:\n");
print(l);

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s