c program for insert at specific position and delete from specific position in singly link list - c program with parth patthar

c program with parth patthar

learn c and c++ in better way and with simple example.

Believe on your own logic

Sunday, September 30, 2018

c program for insert at specific position and delete from specific position in singly link list

#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
struct node *first=NULL,*temp,*prev;
int item,i,p;
void insert()
{
struct node *nn;
nn=((struct node*)malloc(sizeof(nn)));
if(nn==NULL)
{
printf("\n memory not allocate:");
getch();
return;
}
printf("\n enter position for insert:");
scanf("%d",&p);
printf("\n enter item:");
scanf("%d",&item);
nn->info=item;
if(p==1)
{
if(first==NULL)
{
nn->link=NULL;
first=nn;
}
else
{
nn->link=first;
first=nn;
}
return;
}
temp=first;
for(i=2;i<p;i++)
{
temp=temp->link;
}
nn->link=temp->link;
temp->link=nn;
}
void display()
{
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->link;
}
getch();
}
void delet()
{
if(first==NULL)
{
printf("\n list is empty ");
getch();
return;
}
printf("\n enter position for delete:");
scanf("%d",&p);
if(p==1)
{
temp=first;
first=first->link;
free(temp);
return;
}
prev=first;
temp=first->link;
for(i=2;i<p;i++)
{
prev=temp;
temp=temp->link;
}
prev->link=temp->link;
free(temp);
}
void main()
{
int ch;
do
{
clrscr();
printf("\n 0)for exit:");
printf("\n 1)for insert:");
printf("\n 2)for display:");
printf("\n 3)for delete:");
printf("\n enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 0:break;
case 1:insert();
break;
case 2:display();
break;
case 3:delet();
break;
default:printf("\n invalid input:");
getch();
}
}while(ch!=0);
}

No comments:

Post a Comment