Program 7:
Develop a menu driven Program in C for the following operations
on Singly Linked List (SLL) of Student Data with the fields:
USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of
stack)
e. Exit
#include<stdio.h>
#include<stdlib.h>
struct node
{
char USN[10], name[20], branch[10];
int sem;
long int ph;
struct node *link;
};
typedef struct node nd;
# define read(t) \
printf("Enter USN, Name, Branch, Sem and Phone of the student:\n"); \
scanf("%s%s%s%d%ld",(t->USN),(t->name),(t->branch), &(t->sem), &(t->ph));
# define print(t) \
printf("Information to be deleted is...\n"); \
printf("%s\t%s\t%s\t%d\t%ld\n",(t->USN),(t->name),(t->branch),(t->sem),(t->ph));
# define check_empty(f) \
if (f==NULL) \
{ \
printf("SLL is empty\n"); \
return NULL;\
}
1
# define check_empty1(f) \
if (f==NULL) \
{ \
printf("SLL is empty\n"); \
return; \
}
nd* create(nd *);
void status(nd *);
nd* ins_front(nd *);
nd* ins_rear(nd *);
nd* del_front(nd *);
nd* del_rear(nd *);
void display(nd *);
int main()
{
nd * first = NULL;
int ch;
for(;;)
{
printf("1. Create N students\n2. Status of SLL\n");
printf("3. Insert front\n4. Insert rear\n5. Delete
front\n");
printf("6. Delete rear\n7. Display\n8. Exit\nChoice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: first = create(first);break;
case 2: status(first); break;
case 3: first = ins_front(first); break;
case 4: first = ins_rear(first); break;
case 5: first = del_front(first); break;
case 6: first = del_rear(first); break;
case 7: display(first); break;
case 8: exit(0);
}
}
}
2
nd * del_front(nd *f)
{
nd *t;
check_empty(f);
print(f);
t = f->link;
free(f);
return t;
}
nd * del_rear(nd *f)
{
nd *t,*p;
check_empty(f);
for(p=NULL,t=f;t->link!=NULL;p=t,t=t->link);
print(t);
free(t);
if (p!=NULL)
{
p->link=NULL;
return f;
}
else
return NULL;
}
3
nd * ins_rear(nd * f)
{
nd *p=f;
nd *t=(nd*)malloc(sizeof(nd));
t->link=NULL;
read(t);
if (f==NULL)
return t;
for(;p->link!=NULL; p=p->link);
p->link=t;
return f;
}
void status(nd *f)
{
int cnt=0;
check_empty1(f);
for(;f!=NULL;f=f->link,cnt++);
printf("Number of nodes in SLL is %d\n",cnt);
}
nd* create(nd *f)
{
int n,i;
printf("Enter value for n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
f = ins_front(f);
return f;
}
4
nd* ins_front(nd *f)
{
nd *t=(nd*)malloc(sizeof(nd));
read(t);
t->link = f;
return t;
}
void display(nd *f)
{
check_empty1(f);
printf("Contents of the list\n");
while(f!=NULL)
{
printf("%s\t%s\t%s\t%d\t%ld\n",(f->USN),(f->name),(f->branch),(f
->sem),(f->ph));
f = f->link;
}
}