Code
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int id;
struct node* next; //for storing address of next node
}node;
node* create();
node* append(node*);
node* modify(node*);
node* del(node*);
void display(node*);
node* create()
{
node* head;
head=(node*)malloc(sizeof(node)); /*allocating memory to node
and head is pointing to it */
printf("\nEnter employee id ");
scanf("%d",&head->id);
head->next=head;
return head;
}
node* append(node* head)
{
node* curr = (node*)malloc(sizeof(node)); //allocate memory for current node
node* prev = head;
printf("\nEnter employee id ");
scanf("%d",&curr->id);
while(prev->next!=head) //traverse the list and go to the last node
prev = prev->next;
prev->next = curr; /*establish the link between last node(pointed by
prev) and curr node */
curr->next = head;
return head;
}
node* modify(node* head)
{
node* curr=head;
int eid,found=0;
printf("\nEnter Eid of employee whose data is to be modified ");
scanf("%d",&eid);
do //traverse list in search of eid
{
if(curr->id==eid)
{
found = 1;
break;
}
else
curr=curr->next;
}while(curr!=head);
if(found == 1) //eid is found
{
printf("\nEnter employee id ");
scanf("%d",&curr->id);
}
else
printf("\nEmployee id not found");
return head;
}
node* del(node* head)
{
node *prev,*curr=head,*last;
int eid;
printf("\nEnter employee id to be deleted ");
scanf("%d",&eid);
if(curr==NULL)
return NULL;
else if(curr->id==eid && curr->next==curr) //only 1 node
{
free(curr);
return NULL;
}
else if(curr->id==eid && curr->next!=head) //1st node
{
head=head->next;
last = head; //go to last node
do
{
last=last->next;
}while(last->next!=curr);
last->next=head;
free(curr);
return head;
}
else
{
do //search node
{
if(curr->id==eid)
break;
else
{
prev=curr;
curr=curr->next;
}
}while(curr!=head);
if(curr!=head) //if eid found
{
//establish the link between prev & node ahead of curr
prev->next=curr->next;
free(curr);
}
else
printf("\nEmployee id not found");
return head;
}
}
void display(node* head)
{
node* curr=head;
if(curr==NULL)
printf("\nList is empty");
else
{
printf("\n");
do
{
printf("%d---",curr->id);
curr=curr->next;
}while(curr!=head);
}
}
int main()
{
node* head = NULL;
int ch;
do
{
printf("\n1.Create 2.Append 3.Modify 4.Delete 5.Display\nEnter choice ");
scanf("%d",&ch);
switch(ch)
{
case 1:
head = create();
break;
case 2:
head = append(head);
break;
case 3:
head = modify(head);
break;
case 4:
head = del(head);
break;
case 5:
display(head);
break;
}
printf("\nContinue? ");
fflush(stdin);
}while(getchar()=='y');
return 0;
}
O/P
No comments:
Post a Comment