Monday, 23 February 2015

Single Linked List in C


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

struct SLink
{
int Data;
struct SLink *Next;
}*Front,*Rear;

main()
{
int choice;
Home:
clrscr();
printf("\n\t\t\t Single 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 SLink *Source=(struct SLink*)malloc(sizeof(struct SLink));

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

if(Front==NULL)
{
Front=(struct SLink*)malloc(sizeof(struct SLink));
Rear=(struct SLink*)malloc(sizeof(struct SLink));
Front=Rear=Source;
}
else
{
Rear->Next=Source;
Rear=Source;
}
}
Modification()
{
int data, i=0;
struct SLink *Source=(struct SLink*)malloc(sizeof(struct SLink));
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);
i=1;
break;
}
Source=Source->Next;
}
if(i==0)
printf("\n Record Not Found");
getch();
}
Display()
{
struct SLink *Source=(struct SLink*)malloc(sizeof(struct SLink));
Source=Front;
while(Source!=NULL)
{
printf("\n Node Value is :%d",Source->Data);
Source=Source->Next;
}
getch();
}
Deletion()
{
int data;
struct SLink *Source=(struct SLink*)malloc(sizeof(struct SLink));
struct SLink *Forward=(struct SLink*)malloc(sizeof(struct SLink));

Source=Front;

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

if(Source->Data==data)
{
Front=Front->Next;
free(Source);
}
else
while(Source!=NULL)
{
if(Source->Data==data)
{
Forward->Next=Source->Next;
free(Source);
break;
}
Forward=Source;
Source=Source->Next;
}
}

No comments:

Post a Comment