Pages

Friday, December 31, 2010

Adding nodes anywhere in a single linked list

In the previous code, the only way to add a new node to the linked list was to add it at the end of the list, but if required a node can be added to the beginning or the middle of the list. To add a node any where in the list, just replace the add() function given in the previous post with the code given below. The code will ask the user to specify where the new node is to be added - at the end, middle or the beginning.

 void add()
{
    clrscr();
    int c,id;
    person *pers,*ptr,*prev;
    pers=(person *) malloc(sizeof(person));
    if(pers==NULL)
    {
        printf("\nNot enough memory");
        return;
    }
    printf("\nEnter Person Id ");
    scanf("%d",&pers->personid);
    printf("\nEnter Person name ");
    scanf("%s",&pers->name);
    if(start==NULL) // checking if this is the first node
    {
        start=pers; // to make it the first node, make start point to it
        pers->next=NULL;// since it is the first node, its next part will store NULL
    }
    else // from 2nd node onwards
    {
        printf("\n1. Add Person to the end ");
        printf("\n2. Add Person to the beginning");
        printf("\n3. Add Person to the middle");
        printf("\nEnter your choice ");
        scanf("%d",&c);
        if(c==1)
        {
            for(ptr=start;(ptr);ptr=ptr->next) // searching for the last node of the list
                prev=ptr;
            prev->next=pers; // making next of last node point to the new node
            pers->next=NULL; // new node's next is NULL
            printf("\nNode added at the end");
        }
        else if(c==2) // adding a node at the beginning
        {
            pers->next=start;// the new node will point to the current start node
            start=pers; // start will point to the new node.
            printf("\nNode added at the beginning");
        }
        else
        {
            printf("\nEnter Person Id Before which the new node is to be added ");
            scanf("%d",&id);
            for(ptr=start;(ptr);ptr=ptr->next)
            {
                if(ptr->personid==id)
                {
                     pers->=prev->next;
                     prev->next=pers;

                }
                prev=ptr;
            }
        }
    }
    printf("\nPerson Added. Press enter to continue...");
    getch();
    clrscr();
}

0 comments:

Post a Comment