Deletion at given position in Singly Linked list by R4R Team

Function For Deletion At any position in Linked List:

void deletion(int pos)
{
struct node *ptr,*cpt;
int i=1;
ptr=first;
while(1){
if(i++==pos)
break;
cpt=ptr;
ptr=ptr->link;
}
cpt->link=ptr->link;
free(ptr);
}


Whole program-

#include< stdio.h>
#include< conio.h>
#include< alloc.h>
struct node{
struct node *link;
int data;
};
struct node *first=NULL;

void traverse()
{
struct node *ptr=first;
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->link;
}
}

void deletion(int pos)
{
struct node *ptr,*cpt;
int i=1;
ptr=first;
while(1){
if(i++==pos)
break;
cpt=ptr;
ptr=ptr->link;
}
cpt->link=ptr->link;
free(ptr);
}

void main()
{
struct node *cpt,*ptr;
int n,pos;
char ch;
clrscr();
first=(struct node*)malloc(sizeof(struct node));
printf("Enter first element in Linklist\n");
scanf("%d",&first->data);
ptr=first;
do
{
cpt=(struct node*)malloc(sizeof(struct node));
printf("Enter another data\n");
scanf("%d",&cpt->data);
ptr->link=cpt;
ptr=ptr->link;
printf("Continue(y/n) ?");
ch=getch();
}while(ch=='y');
ptr->link=NULL;
printf("Linklist is\n");
traverse();
printf("Enter position to delete the number\n");
scanf("%d",&pos);
deletion(pos);
printf("Linklist After Deletionn");
traverse();
getch();
}


output-

Enter first element in Linked list
2
Enter another data
4
Continue(y/n)?
Enter another data
1
Continue(y/n) ?
Enter another data
9
Continue(y/n) ?
Enter another data
0
Continue(y/n) ?
Linklist is :
2 4 1 9 0
Enter position to delete the number
3
Linklist After Deletion
2 4 9 0




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!