Friday, September 3, 2010

C Program to insert an element after a specified node

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
     int data;
     struct node *link;
};
void append(struct node**,int);
void display(struct node*);
void add_after(struct node*,int,int);
void main()
{
    struct node *head;

    int n,lo;
    clrscr();
    head=NULL;
    append(&head,5);
    append(&head,6);
    append(&head,7);
    append(&head,8);
    display(head);

    printf(" \n Enter the number you want to insert ");

    scanf("%d",&n);

    printf(" \n Enter the location after which you want to insert ");

    scanf("%d",&lo);
    add_after(head,lo,n);
    display(head);
    getch();
}
void append(struct node **q,int num)
{
    struct node *temp,*r;
    temp=*q;

    if(temp==NULL)  /* If list is empty , create first node */
    {
         temp=(struct node*)malloc(sizeof(struct node));
         temp->data=num;
         temp->link=NULL;
         *q=temp;
    }
    else
    {
        temp=*q;
        while(temp->link !=NULL)
        temp=temp->link;

        r=(struct node*)malloc(sizeof(struct node));
        r->data=num;
        r->link=NULL;
        temp->link=r;
    }
}
void display(struct node *start)
{
    printf("\n");
    printf(" The Linked List is :\n");
    /* Traverse the entire linked list */
    while(start != NULL)
    {
        printf("   %d",start->data);
        start=start->link;
    }

}
void add_after(struct node*q,int loc,int num)
{
struct node *temp,*r;
int i;

temp=q;
for(i=1;i<=loc-1;i++)
{
temp=temp->link;
if(temp==NULL)
{

printf("\n There are less than %d elements in the list",loc);
return;
}
}
r=(struct node*)malloc(sizeof(struct node));
r->data=num;
r->link=temp->link;
temp->link=r;
}


No comments:

Post a Comment