Write
C program to Delete, insert nodes at Beginning, Middle and at End using
functions in Double Linked List
#include<stdio.h>
struct dnode
{
struct dnode *Llink;
int data;
struct dnode *Rlink;
};
struct dnode *L,*R;
struct dnode *getnode()
{
struct dnode *p;
p=(struct dnode *) malloc(sizeof(struct
dnode));
printf("Enter the data in the
Node:");
scanf("%d",&p->data);
p->Llink=NULL;
p->Rlink=NULL;
return p;
}
void creatednodes()
{
struct dnode *f,*t,*temp;
int ct=0;
char ch='Y';
while(ch=='Y'|| ch=='y')
{
if(ct==0)
{
f=getnode();
ct++;
}
else
{
temp=f;
while(temp->Rlink!=NULL)
{
temp=temp->Rlink;
}
t=getnode();
temp->Rlink=t;
t->Llink=temp;
}
printf("do you want to continue:
");
fflush(stdin);
ch=getchar();
}
L=f;
R=t;
}
int countdnodes(struct dnode *L)
{
struct dnode *temp;
int ct=0;
temp=L;
while(temp!=NULL)
{
ct++;
temp=temp->Rlink;
}
return ct;
}
void displaynodesLtoR(struct dnode *L)
{
struct dnode *temp;
temp=L;
printf("NULL<-->");
while(temp!=NULL)
{
printf("%d<-->",temp->data);
temp=temp->Rlink;
}
printf("NULL\n");
}
void displaynodesRtoL(struct dnode *R)
{
struct dnode *temp;
temp=R;
printf("NULL<-->");
while(temp!=NULL)
{
printf("%d<-->",temp->data);
temp=temp->Llink;
}
printf("NULL\n");
}
struct dnode *insertfirstdnode(struct dnode
*L)
{
struct dnode *t;
t=getnode();
t->Rlink=L;
L->Llink=t;
L=t;
return L;
}
struct dnode *insertlastdnode(struct dnode
*R)
{
struct dnode *t;
t=getnode();
R->Rlink=t;
t->Llink=R;
R=t;
return R;
}
struct dnode *insertmiddlednode(struct dnode
*L,int pos)
{
struct dnode *temp,*t;
int i;
temp=L;
for(i=1;i<pos-1;i++)
{
temp=temp->Rlink;
}
t=getnode();
t->Llink=temp;
t->Rlink=temp->Rlink;
temp->Rlink->Llink=t;
temp->Rlink=t;
return L;
}
void Insertdnodes(int pos)
{
struct dnode *t,*temp;
int ct,i;
ct=countdnodes(L);
if(pos==1)
{
t=getnode();
t->Rlink=L;
L->Llink=t;
L=t;
}
else if(pos>ct)
{
t=getnode();
R->Rlink=t;
t->Llink=R;
R=t;
}
else
{
temp=L;
for(i=1;i<pos-1;i++)
{
temp=temp->Rlink;
}
t=getnode();
t->Llink=temp;
t->Rlink=temp->Rlink;
temp->Rlink->Llink=t;
temp->Rlink=t;
}
}
void deletednodes(int pos)
{
struct dnode *t,*t1,*t2;
int ct,i;
ct=countdnodes(L);
if(pos==1)
{
t=L;
L=L->Rlink;
t->Rlink=NULL;
L->Llink=NULL;
free(t);
}
else if(pos==ct)
{
t=R;
R=t->Llink;
R->Rlink=NULL;
t->Llink=NULL;
free(t);
}
else
{
t=L;
for(i=1;i<pos;i++)
{
t=t->Rlink;
}
t->Llink->Rlink=t->Rlink;
t->Rlink->Llink=t->Llink;
free(t);
}
}
void main()
{
int ct;
clrscr();
creatednodes();
printf("display nodes left to right\n");
displaynodesLtoR(L);
printf("display nodes right to
left\n");
displaynodesRtoL(R);
ct=countdnodes(L);
printf("number of
nodes=%d\n",ct);
/* Insertdnodes(3);
displaynodesLtoR(L);
displaynodesRtoL(R);*/
deletednodes(2);
displaynodesLtoR(L);
displaynodesRtoL(R);
/*
L=insertfirstdnode(L);
displaynodesLtoR(L);
displaynodesRtoL(R);
R=insertlastdnode(R);
displaynodesLtoR(L);
displaynodesRtoL(R);
L=insertmiddlednode(L,3);
displaynodesLtoR(L);
displaynodesRtoL(R);*/
getch();
}
No comments:
Post a Comment