Lab_5
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int rollno;
char name[20];
struct node *next;
};
struct node *head,*temp;
void main()
{
int option;
void create();
void display();
void insertbegin();
void dele();
while(1)
{
printf("\n\n\nLinked List Implementation\n");
printf(" 1.Create a Linked List\n ");
printf(" 2.Insert node at the beginning\n");
printf(" 3.Delete based on Rollno\n ");
printf(" 4.Display Linked List\n ");
printf(" 5.Exit \n");
printf("\n\n\n\Enter your option: ");
scanf("%d",&option);
switch(option)
{
case 1: create();
break;
case 2: insertbegin();
break;
case 3: dele();
break;
case 4: display();
break;
case 5: return;
default:printf("\nInvalid option");
}
}
}
void create()
{
char ch='y';
struct node *last;
struct node *newnode;
head=NULL;
while(ch=='y')
{
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("\n Memory Overflow!!!");
getch();
exit(0);
}
newnode->next=NULL;
printf("\n Enter Rollno and Name:");
scanf("%d%s",&newnode->rollno,newnode->name);
if(head==NULL)
head=last=newnode;
else
{
last->next=newnode;
last=newnode;
}
printf("\n Do you want to continue?");
fflush(stdin); // to clear the memory
scanf("%c",&ch); // or else type space %c to avoid skipping of input
}
}
void display()
{
if(head==NULL)
printf("\n List is empty");
else
{
temp=head;
printf("\n Name \t\t Regno \n");
while(temp!=NULL)
{
printf("%s\t\t%d\n",temp->name,temp->rollno);
temp=temp->next;
}
}
}
void insertbegin()
{
struct node newnode;
newnode=(struct node)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("\n Overflow");
getch();
exit(0);
}
printf("\n Enter Rollno and Name:");
scanf("%d%s",&newnode->rollno,newnode->name);
newnode->next=head;
head=newnode;
}
void dele()
{
struct node* prev;
int rno;
printf("\n Enter Rollno to delete:");
scanf("%d",&rno);
prev=NULL;
temp=head;
while(temp!=NULL)
{
if(rno==temp->rollno)
{
printf("\n Node is deleted");
if(temp==head)
{
head=head->next;
free(temp);
return;
}
else
{
prev->next=temp->next;
free(temp);
return;
}
}
else
{
prev=temp;
temp=temp->next;
}
}
if(temp==NULL)
printf("\n Node Not found");
}