Monday 23 February 2015

Double Linked List Program in C


#include<stdio.h>
#include<conio.h>

struct DLink
{
int Data;
struct DLink *Forw;
struct DLink *Back;
}*Front,*Rear;

main()
{
int choice;
Home:
clrscr();
printf("\n\t\t\t Double Linked List Demo \n");
printf("\n\t\t\t1.. Addition");
printf("\n\t\t\t2.. Modification");
printf("\n\t\t\t3.. Deletion");
printf("\n\t\t\t4.. View");
printf("\n\t\t\t5.. Exit");
printf("\n\n\t\t Enter Your Choice\n");
scanf("%d",&choice);

switch(choice)
{

case 1:
Addition();
break;
case 2:
Modification();
break;
case 3:
Deletion();
break;
case 4:
Display();
break;
case 5:
exit(0);
default:
printf("\n Wrong Press");
}
goto Home;
}

Addition()
{
struct DLink *Source=(struct DLink*)malloc(sizeof(struct DLink));

printf("\n Enter Data For Node\n");
scanf("%d",&Source->Data);
Source->Forw=NULL;
Source->Back=NULL;


if(Front==NULL)
{
Front=(struct DLink*)malloc(sizeof(struct DLink));
Rear=(struct DLink*)malloc(sizeof(struct DLink));
Front=Rear=Source;
}
else
{
Rear->Forw=Source;
Source->Back=Rear;
Rear=Source;
}
}

Modification()
{
int data;
struct DLink *Source=(struct DLink*)malloc(sizeof(struct DLink));
Source=Front;
printf("\n Enter Node Value To Modify\n");
scanf("%d",&data);

while(Source!=NULL)
{
if(Source->Data==data)
{
printf("\n Enter New Value To Modify\n");
scanf("%d",&Source->Data);
break;
}
Source=Source->Forw;
}
}

Display()
{
struct DLink *Source=(struct DLink*)malloc(sizeof(struct DLink));
Source=Front;
while(Source!=NULL)
{
printf("\n Node Value is :%d",Source->Data);
Source=Source->Forw;
}
getch();
}

Deletion()
{
int data;
struct DLink *BTemp=(struct DLink*)malloc(sizeof(struct DLink));
struct DLink *FTemp=(struct DLink*)malloc(sizeof(struct DLink));
struct DLink *Source=(struct DLink*)malloc(sizeof(struct DLink));

Source=Front;

printf("\n Enter Node Value To Delete\n");
scanf("%d",&data);

if(Source->Data==data)
{
Front=Front->Forw;
Front->Back=NULL;
free(Source);
}
else
while(Source!=NULL)
{
if(Source->Data==data)
{
BTemp=Source->Back;
FTemp=Source->Forw;
BTemp->Forw=FTemp;
FTemp->Back=BTemp;
free(Source);
break;
}
Source=Source->Forw;
}
}

No comments:

Post a Comment