Deletion at any position | SLL | C Program
struct node
{
int data;
struct node *next;
};
struct node *start=NULL;
main()
{
int i,value,ne,pos,invalid; // ne=Number of element in list, pos= position
struct node *n,*temp,*del;
n=malloc(sizeof(struct node));
printf("\n\n\tHow many value do you want to Enter in List: ");
scanf("%d",&ne);
printf("\nEnter first data for list: ");
scanf("%d",&value);
n->data=value;
n->next=NULL;
start=n;
for(i=2;i<=ne;i++)
{
n=malloc(sizeof(struct node));
printf("Enter next data: ");
scanf("%d",&value);
n->data=value;
n->next=NULL;
temp=start;
while(temp->next!=NULL)
temp=temp->next;
temp->next=n;
}
// for display
if(start==NULL)
printf("\n\t** List is empty **");
else
{
temp=start;
printf("\n\tData in the List: ");
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
//for Deleting at any position
printf("\n\n\tWhich position do you want to Delete: ");
scanf("%d",&pos);
temp=start;
if(pos==1)
{
start=start->next;
free(temp);
}
else
{
for(i=1;i<pos-1;i++)
{
if(start==NULL)
printf("List is empty");
else
temp=temp->next;
if(temp->next==NULL)
break;
}
if(temp->next==NULL)
{
invalid=1;
printf("\n\t\t*** Invalid Position ***");
}
else
{
del=temp->next;
temp->next=del->next;
free(del);
}
}
// for display
if(start==NULL)
printf("\n\t** List is empty **");
else
{
if(invalid==1)
printf("\n\t** Could not Delete Data due to invalid position **");
else
{
if(pos==1) //for print deleted position
printf("\n\n\t** %dst position deleted successfully **",pos);
else
if(pos==2)
printf("\n\n\t** %dnd position deleted successfully **",pos);
else
if(pos==3)
printf("\n\n\t** %drd position deleted successfully **",pos);
else
printf("\n\n\t** %dth position deleted successfully **",pos);
}
temp=start;
printf("\n\n\tUpdated List: ");
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
getch();
}
OUTPUT:
0 Comments
Please do not enter any spam link in the comment box.