program on Link list in c.

here we are understasnd  Link list by a example in which we creat a Link list and insert node  in the list and creat a function to view the list and we also creat a function for delete node from list. This is menu based program.
#include<stdio.h>
struct node
{
int data;
struct node *link;
};
struct node *head=NULL;


//function to create node


struct node *CreatNode()
{
struct node *n;
n=(struct node *) malloc(sizeof(struct node));
return(n);
}


// function for insert node at end


void InsertNodeEnd()
{
struct node *t,*temp;
t=CreatNode();
printf(“Enter a value”);
scanf(“%d”,&t->data);
t->link=NULL;
if(head==NULL)
head=t;
else
{
temp=head;
while(temp->link!=NULL)
temp=temp->link;
temp->link=t;
}
}


// function for insert node at starting


void InsertNodestart()
{
struct node *t,*temp;
t=CreatNode();
printf(“Enter a value”);
scanf(“%d”,&t->data);
if(head==NULL)
{
head=t;
t->link=NULL;
}
else
{
t->link=head;
head=t;
}
}


// function for delete node from starting


struct node *deleteNodestart()
{
struct node *t;
if(head==NULL)
printf(“List is Empty”);
else
{
t=head;
head=head->link;
free(t);
}
}


// function for delete node from end


struct node *deleteNodeend()
{
struct node *t,*temp;
if(head==NULL)
printf(“List is Empty”);
if(head->link==NULL)
{
temp=head;
head=NULL;
free(temp);
}
else
{
t=head;
while(t->link->link!=NULL)
t=t->link;
t->link=NULL;
temp->data=t->link->data;
temp->link=NULL;
free(temp);
}
}


// function for display list


void viewlist()
{
struct node *t;
if(head==NULL)
printf(“List is Empty”);
else
{
t=head;
while(t!=NULL)
{
printf(“%d “,t->data);
t=t->link;
}
}
}


    // driver function
    
void main()
{
int ch;
while(1)
{
clrscr();
printf(“Pressn”);
printf(“1. Add valuen”);
printf(“2. Delete valuen”);
printf(“3. viewn”);
printf(“4. Exitn”);
printf(“Enter YOur choicen”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“Pressn”);
printf(“1. at startingn”) ;
printf(“2. at endn”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
InsertNodestart();
break;
case 2:
InsertNodeEnd();
break;
default:
printf(“Invaild key”);
}
break;
case 2:
printf(“Pressn”);
printf(“1. From startingn”);
printf(“2. From endn”) ;
scanf(“%d”,&ch);
switch(ch)
{
case 1:
deleteNodestart();
break;
case 2:
deleteNodeend();
break;
default:
printf(“Invaild key”);
}
break;
case 3:
viewlist();
break;
case 4:
exit(0);
default:
printf(“Invaild key”);
}
getch();
}
}

One thought on “program on Link list in c.

Leave a Reply

Your email address will not be published.