#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student
{
int rollno;
char name[15];
struct student *link;
};
typedef struct student *node;
node Linsert(int id, char name[], node head)
{
node temp,q;
temp = (node) malloc (sizeof(struct student));
temp->rollno = id;
strcpy(temp->name,name);
temp->link = NULL;
if(head == NULL)
return temp;
else
{
q=head;
while(q->link!=NULL)
q=q->link;
q->link=temp;
return head;
}
}
node Ldelete(int id, node head)
{
node prev,cur;
if(head == NULL)
{
printf("No Item to Delete\n");
return head;
}
if (id == head->rollno)
{
cur=head;
head=head->link;
printf("Record deleted\n");
free(cur);
return head;
}
prev = NULL;
cur = head;
while (cur != NULL && id != cur->rollno)
{
prev = cur;
cur = cur->link;
}
if(cur == NULL)
{
printf("Item not found\n");
return head;
}
prev->link = cur->link;
printf("Record deleted\n");
free(cur);
return head;
}
void Lsearch (int id,node head)
{
node cur;
int pos;
if (head == NULL)
{
printf("List is Empty\n");
return;
}
cur = head;
pos = 1;
while (cur != NULL && id != cur->rollno)
{
cur = cur->link;
pos++;
}
if (cur == NULL)
{
printf("Record not found\n");
return;
}
else
printf("Record found at position %d\n ",pos);
}
void Ldisplay (node head)
{
node temp;
if (head == NULL)
{
printf("List is empty\n");
return;
}
printf("\nThe contents of the list are :\n");
temp = head;
printf("RollNo\tNAME\n");
while (temp != NULL)
{
printf("%d\t%s\n",temp->rollno, temp->name);
temp = temp->link;
}
}
void main()
{
node head = NULL;
int opt,id;
char sname[15];
printf("**** SINGLY LINKED LIST OPERATIONS****\n");
printf("1: Insert a record\n");
printf("2. Delete a record\n");
printf("3. Search a record\n");
printf("4. Display the contents\n");
printf("5: EXIT\n");
while(1)
{
printf("Enter your option\n");
scanf("%d",&opt);
switch (opt)
{
case 1:
printf("Enter the student roll no ");
scanf("%d",&id);
printf("Enter the student name ");
scanf("%s",&sname);
head = Linsert(id,sname,head);
break;
case 2:
printf("Enter the student roll no. to be deleted ");
scanf("%d",&id);
head = Ldelete(id,head);
break;
case 3:
printf("Enter the student roll no. to be searched ");
scanf("%d",&id);
Lsearch(id,head);
break;
case 4:
Ldisplay(head);
break;
case 5:
exit(0);
break;
default:
printf("Invalid option\n");
break;
}
}
}
 
 
0 Comments