Welcome To Uday Satya Blog

18 . INSERT BETWEEN LL



/* ***************************************************
    18 . TO INSERT ELEMENT IN BETWN TWO ELEMENTS
   *************************************************** */
#include<*stdio.h>
#include<*conio.h>
#include<*malloc.h>
void main()
{
struct link
{
int info;
struct link*ptr;
};
int ele;
struct link*head,*cur,*temp,*temp1;
char ch='y';
clrscr();
head=(struct link*)malloc(sizeof(struct link));
temp1=(struct link*)malloc(sizeof(struct link));
printf("\n enter the head element : ");
scanf("%d",&head->info);
cur=head;
cur->ptr=NULL;
do
{
temp=(struct link*)malloc(sizeof(struct link));
printf("\n\n enter number to be inserted : ");
scanf("%d",&temp->info);
printf("\n\n do you want to insert more (yes,no) : ");
ch=getch();
temp->ptr=NULL;
cur->ptr=temp;
cur=cur->ptr;
}while(ch=='y');
cur=head;
printf("\n\n elements before insertion : ");
while(cur!=NULL)
{
printf("%d\t",cur->info);
cur=cur->ptr;
}
cur=head;
temp=cur->ptr;
printf("\n\n enter the element before which you want to insert : ");
scanf("%d",&ele);
while(cur->info!=ele&&cur!=NULL)
{
cur=cur->ptr;
}
if(cur->info==ele)
{
printf("\n\n enter new element to be inserted : ");
scanf("%d",&temp1->info);
cur=head;
temp=cur->ptr;
while(temp->info!=ele)
{
cur=cur->ptr;
temp=temp->ptr;
}
cur->ptr=temp1;
temp1->ptr=temp;
cur=head;
printf("\n\n elements after insertion :\n");
while(cur!=NULL)
{
printf("\t %d",cur->info);
cur=cur->ptr;
}
}
else
{
printf("\n\n element does not exist");
}
getch();
}

output

 enter the head element : 1

 enter number to be inserted : 2

 do you want to insert more (yes,no) :

 elements before insertion : 1  2

 enter the element before which you want to insert : 2

 enter new element to be inserted : 3

 elements after insertion :
        1       3       2

0 comments:

Post a Comment