Header Ads Widget

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("Press\n");
printf("1. Add value\n");
printf("2. Delete value\n");
printf("3. view\n");
printf("4. Exit\n");
printf("Enter YOur choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Press\n");
printf("1. at starting\n") ;
printf("2. at end\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
InsertNodestart();
break;
case 2:
InsertNodeEnd();
break;
default:
printf("Invaild key");
}
break;
case 2:
printf("Press\n");
printf("1. From starting\n");
printf("2. From end\n") ;
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();
}
}


Post a Comment

1 Comments