Program to insert a node in the linked list

August 29th, 2009  |  Published in Amit Sahrawat, Data Structures, Linux Sample Programs








/* Structure for a linked list*/
struct list{
    int num;
    struct list* next; /* pointer to next node in list*/
};

/* Function to insert node into a linked list, given the head pointer and the value to be inserted */
void insert(struct list **head,int value)
{
    struct list* temp = NULL;
    temp = *head;
    if(NULL == *head)
    {
        *head = (struct list*) malloc(sizeof(struct list));
        (*head)->num = value;
        (*head)->next= NULL;
    }else
    {
        while(temp->next != NULL)
        {
            temp = temp->next;   
        }
        temp->next = (struct list*) malloc(sizeof(struct list));
        temp->next->num = value;
        temp->next->next = NULL;
    }
}

/* Function to use the linked list functions*/
int main()
{
    struct list* node = NULL;
    struct list* new = NULL;
    int i;

    for(i=0; i < 10; i++)
    {
        insert(&node,i);
    }
}

Subscribe

Get articles in your inbox.

Enter your email address:

Join Us

Twitter Chatter


Recommendations

Archives

Categories