Deletion at any position in doubly linked list by R4R Team

deletion() function are used to delete the item in the doubly linked list at given position.
traverse() function are used to get all data from the doubly linked list.

program-

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

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

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

void main()
{
struct node *cpt,*ptr;
char ch;
clrscr();
first=(struct node*)malloc(sizeof(struct node));
printf("Enter first element in Linklist\n");
scanf("%d",&first->data);
first->pre=NULL;
ptr=first;
do
{
cpt=(struct node*)malloc(sizeof(struct node));
printf("Enter another data\n");
scanf("%d",&cpt->data);
ptr->next=cpt;
cpt->pre=ptr;
ptr=ptr->next;
printf("Continue(y/n) ?");
ch=getch();
}while(ch=='y');
ptr->next=NULL;
last=ptr;
printf("\nDoubly Linked-list is\n");
traverse();
printf("\nAfter deletion of 4th element\n");
deletion(4);
traverse();
printf("\nAfter deletion of 2nd element\n");
deletion(2);
traverse();
getch();
}


output-

Enter first element in Linklist
4
Enter another data
5
Continue(y/n)?
Enter another data
1
Continue(y/n)?
Enter another data
9
Continue(y/n)?
Enter another data
0
Continue(y/n)?
Doubly Linked-List is
4 5 1 9 0
After deletion of 4th element
4 5 1 0
After deletion of 2nd element
4 1 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!