How to insert a node in a linked list recursively?

A linked list is a recursive data structure. A recursive data structure is a data structure that has the same form regardless of the size of the data. If you haven’t already gone through the concepts of a linked list, I recommend you to go through my previous article on linked list first.

The recursive method for inserting a node in a singly linked list is simple and given below:

struct node *insert(struct node *p, int n)
        struct node *temp;
                p=(struct node *)malloc(sizeof(struct node));
                p-> data = n;
                p-> link = NULL;
                p->link = insert(p->link,n);/* the while loop replaced by
                                               recursive call */
        return (p);
  1. Leave a comment

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 )

Google+ photo

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


Connecting to %s

%d bloggers like this: