#include #include main() { typedef struct Car { char Make[10]; char Model[10]; int year; int ID; struct Car *ptr; } Cars; Cars *c1, *c2, *prev, *head=NULL; char s[10], s1[50]; int i, Id_delete, found=0;; printf("Enter a to add, d to delete, or l to list\n"); while(fgets(s, sizeof(s), stdin) != NULL) { //remove \n i=0; while(s[i] != '\n') i++; s[i]='\0'; if( strcmp(s, "a") ==0) { //Add a car c2=malloc(sizeof(Cars)); if(c2 == NULL) {perror("can not allocate memory"); return(-1);} printf("Enter the Make, Model, year, ID separated by one space\n"); fgets(s1, sizeof(s1), stdin); printf("1111\n"); sscanf(s1, "%s %s %d %d", c2->Make, c2->Model, &c2->year, &c2->ID); c2->ptr=NULL; //put it in the list //if the list is empty if(!head) head = c2; else { //not empty c1 = head; while(c1->ptr != NULL) c1 = c1->ptr; // Now, wc1 is pointing to the last node in the list c1->ptr = c2; } } else if (strcmp(s, "l")==0) { //list the list printf("printing\n"); c1=head; while(c1 != NULL) { printf("%s %s %d %d \n",c1->Make, c1->Model, c1->year, c1->ID); c1=c1->ptr; } } else if (strcmp(s, "d") ==0) { //delete //get the ID of the car to delete printf("Enter the ID of the Car to delete : "); fgets(s1, sizeof(s1), stdin); sscanf(s1,"%d",&Id_delete); if(head == NULL) printf("Empty list\n"); else if (head->ptr == NULL) { // only one node if(head->ID == Id_delete) { free(head); head=NULL;} else printf("No such ID to delete\n"); } else { // more than one node //search for the ID in the list c1=head; prev=head; while(c1->ID != Id_delete) { prev=c1; c1 = c1->ptr;} if(c1 == NULL) printf("No such ID to delete\n"); else { // delete this node printf("Now I am here\n"); printf("%d %d \n",prev->ID, c1->ID); if (c1==head) head=head->ptr; else prev->ptr = c1->ptr; free(c1); } } } else printf("No such command\n"); printf("Enter a to add, d to delete, or l to list\n"); } }