Monday, 24 September 2012

Singal Link List Operation using C Language


In computer science, a linked listis a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a datum and a reference (in other words, a link) to the next node in the sequence; more complex variants add additional links. This structure allows for efficient insertion or removal of elements from any position in the sequence.
#include<stdio.h>
#include<conio.h>
typedef struct st_tag
{
int data;
struct st_tag *next;
}node;
/* Function Prototype */
node* create(int);
void addbegin(node**,int);
void addlast(node**,int);
void addbefore(node**,int,int);
void addafter(node**,int,int);
void del(int,node**);
void print(node*);
void main()
{
node *start=NULL;
int n,s,opt;



do
{
clrscr();
printf("\n1. Print\n2. Add Begin\n3. Add Last\n4. Add Before to given number\n5. Add after to given number\n6. Delete\n0. Exit \nEnter your choice>> ");
fflush(stdin);
scanf("%d",&opt);
switch(opt)
{
case 1:
print(start);
getch();
break;

case 2:
printf("Enter Number for add begin>> ");
scanf("%d",&n);
addbegin(&start,n);
break;
case 3:
printf("Enter Number for add Last>> ");
scanf("%d",&n);
addlast(&start,n);
break;
case 4:
printf("Enter number for search>> ");
scanf("%d",&s);
printf("enter number for Add in List>> ");
scanf("%d",&n);
addbefore(&start,s,n);
break;
case 5:
printf("Enter number for search>> ");
scanf("%d",&s);
printf("enter number for Add in List>> ");
scanf("%d",&n);
addafter(&start,s,n);
break;
case 6:
printf("Enter number for delete>> ");
scanf("%d",&n);
del(n,&start);
break;

case 0:
break;
default:
printf("\nInvalid Choice ");
}
}while(opt!=0);
}



node* create(int n)
{
node *nw;
nw=(node*) malloc(sizeof(node));
nw->data=n;
nw->next=NULL;
return(nw);
}
void addbegin(node **st,int n)
{
node *nw=create(n);
if(*st==NULL)
{
*st=nw;
}
else
{
nw->next=*st;
*st=nw;
}

}
void print(node *st)
{
node *pt;
for(pt=st;pt!=NULL;pt=pt->next)

printf("[ %d ]",pt->data);

}
void addlast(node **st,int n)
{
node *nw=create(n),*pt;
if(*st==NULL)
{
*st=nw;
}
else
{
for(pt=*st;pt->next!=NULL;pt=pt->next);
pt->next=nw;
}


}
void addbefore(node **st,int s,int n)
{
node *nw,*pre,*pt;
for(pt=*st;pt!=NULL;pre=pt,pt=pt->next)
{
if(pt->data==s)
{
break;
}
}
if(pt==NULL)
{
printf("\nSearch Value not found");
getch();
}
else
{
nw=create(n);
if(pt==*st)
{
nw->next=*st;
*st=nw;
}
else
{
nw->next=pre->next;
pre->next=nw;
}
}
}
void addafter(node **st,int s,int n)
{
node *nw,*pt;
for(pt=*st;pt!=NULL;pt=pt->next)
{
if(pt->data==s)
{
break;
}
}
if(pt==NULL)
{
printf("\nSearch Value not found");
getch();
}
else
{
nw=create(n);
nw->next=pt->next;
pt->next=nw;
}
}
void del(int n,node **st)
{
node *pt,*pre;
for(pt=*st;pt!=NULL;pre=pt,pt=pt->next)
{
if(pt->data==n)
{
break;
}
}
if(pt==NULL)
{
printf("Search value not found");
getch();
}
else
{
if(pt==*st)
{
*st=pt->next;
free(pt);
}
else
{
pre->next;pt->next;
free(pt);
}
}
}