EX.NO:5
LINKED LIST IMPLEMENTATION – LIST
PROGRAM: #include<stdio.h> #include #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head,*temp; void display(); void add() { struct node *add; add=(struct node*)malloc(sizeof(struct node)); printf("Enter the data\n"); scanf("%d",&add->data); if(head==NULL) { head=add; head->next=NULL; temp=add; } else { temp->next=add; add->next=NULL; temp=add; } /*display();*/ } void dele() { struct node *del; int num,found=0; printf("Enter the number to be deleted\n"); scanf("%d",&num); for(del=head;del!=NULL;del=del->next) { if(head->data==num) { head=head->next;
found=1; } else if(del->next->data==num) { del->next=del->next->next; found=1; } } if(found==1) printf("%d was deleted\n",num); } void insert() { struct node *ins,*trav; int no,x; ins=(struct node*)malloc(sizeof(struct node)); printf("Enter the data after which the new data has to be entered\n"); scanf("%d",&no); printf("Enter the data to be inserted\n"); scanf("%d",&ins->data); for(trav=head;trav!=NULL;trav=trav->next) { if(trav->data==no) { ins->next=trav->next; trav->next=ins; x=1; } } if(x==1) printf("The number has been inserted\n"); } void modify() { struct node *mod,*data; int x,num,no; printf("Enter the number to be modified\n"); scanf("%d",&no); printf("Enter the new number\n"); scanf("%d",&num); for(mod=head;mod!=NULL;mod=mod->next) { if(mod->data==no) { mod->data=num; x=1;
} } if(x==1) printf("The number has been modified\n"); } void display() { struct node *disp; if(head==NULL) printf("The list is empty\n"); else { for(disp=head;disp!=NULL;disp=disp->next) { printf("%d\t",disp->data); } } } void main() { int ch; char a='y'; clrscr(); printf("1.Add\t2.Delete\t3.Insert\t4.Modify\t5.Display"); do { printf("\nEnter the choice\n"); scanf("%d",&ch); switch(ch) { case 1: add(); break; case 2: dele(); break; case 3: insert(); break; case 4: modify(); break; case 5: display(); break; default:
printf("\nEnter correct choice\n"); } printf("\nDo you want to continue(y/n):\n"); a=getch(); }while(a=='y'); getch(); }