Reverse of a singly linked list using recursion

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

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

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)
printf("%d ", l->data);
l = l->next;


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");

l = reverse(l);

printf("After reverse:\n");


Leave a Reply

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

You are commenting using your 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