Slip 8-1: Implement a list library (singlylist.h) for a singly linked list of integer With the operations create, delete specific element and display. Write a menu driven program to call these operations.
Solution :
Header File : singlylist.h
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *f;
void create()
{ int n,i;
struct node *s;
printf("Enter how many nodes ");
scanf("%d",&n);
f= (struct node *)malloc(sizeof(struct node));
printf("Enter data ");
scanf("%d",&f->data);
s=f;
for(i=1;i<n;i++)
{
s->next=(struct node*)malloc(sizeof(struct node));
s=s->next;
printf("Enter data ");
scanf("%d",&s->data);
}
s->next=NULL;
}
void display()
{ struct node *s;
for(s=f;s!=NULL;s=s->next)
{
printf("| %d |-> ",s->data);
}
}
void Delete()
{ int p,cnt=0,i;
struct node *temp,*s;
printf("Enter position to delete a node ");
scanf("%d",&p);
for(s=f;s!=NULL;s=s->next)
{ cnt++;
}
if(p==1)
{
temp=f;
f=f->next;
free(temp);
}
else if(p==cnt)
{
for(i=1,s=f;i<p-1;i++)
{ s=s->next;
}
temp=s->next;
s->next=NULL;
free(temp);
}
else if(p>1 && p<cnt)
{
for(i=1,s=f;i<p-1;i++)
{ s=s->next;
}
temp=s->next;
s->next=temp->next;
free(temp);
}
else
printf("Invalid Position ");
}
Program File :
#include<stdio.h>
#include”singlylist.h”
main()
{ int ch;
do
{
printf("\n1.Create\n2.Display\n3.Delete \n0.Exit");
printf("Enter choice ");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:display();
break;
case 3:Delete();
break;
case 0:break;
default:printf("\nInvalid choice");
}
}while(ch!=0);
}
Header File : singlylist.h
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *f;
void create()
{ int n,i;
struct node *s;
printf("Enter how many nodes ");
scanf("%d",&n);
f= (struct node *)malloc(sizeof(struct node));
printf("Enter data ");
scanf("%d",&f->data);
s=f;
for(i=1;i<n;i++)
{
s->next=(struct node*)malloc(sizeof(struct node));
s=s->next;
printf("Enter data ");
scanf("%d",&s->data);
}
s->next=NULL;
}
void display()
{ struct node *s;
for(s=f;s!=NULL;s=s->next)
{
printf("| %d |-> ",s->data);
}
}
void Delete()
{ int p,cnt=0,i;
struct node *temp,*s;
printf("Enter position to delete a node ");
scanf("%d",&p);
for(s=f;s!=NULL;s=s->next)
{ cnt++;
}
if(p==1)
{
temp=f;
f=f->next;
free(temp);
}
else if(p==cnt)
{
for(i=1,s=f;i<p-1;i++)
{ s=s->next;
}
temp=s->next;
s->next=NULL;
free(temp);
}
else if(p>1 && p<cnt)
{
for(i=1,s=f;i<p-1;i++)
{ s=s->next;
}
temp=s->next;
s->next=temp->next;
free(temp);
}
else
printf("Invalid Position ");
}
Program File :
#include<stdio.h>
#include”singlylist.h”
main()
{ int ch;
do
{
printf("\n1.Create\n2.Display\n3.Delete \n0.Exit");
printf("Enter choice ");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:display();
break;
case 3:Delete();
break;
case 0:break;
default:printf("\nInvalid choice");
}
}while(ch!=0);
}
Comments
Post a Comment