2) Modify the append_to_list function so an equipment is inserted into an ordere
ID: 3713487 • Letter: 2
Question
2) Modify the append_to_list function so an equipment is inserted into an ordered list (by type, then by description) and the list remains ordered after the insertion. For example, dumbbell should be before stability ball in the list; stability ball, large should be beforestability ball, small in the list.
Here is the code:
struct equipment *append_to_list(struct equipment *list){
struct equipment *temp = (struct equipment *)malloc(sizeof(struct equipment));
printf(" Enter equipment type : ");
read_line(temp->type, NAME_LEN);
printf(" Enter description: ");
read_line(temp->description, NAME_LEN);
printf(" Please enter quantity: ");
scanf("%d",&temp->quantity);
temp->next = NULL;
if(list == NULL){
list = temp;
}
else{
struct equipment *temp2 = list, *prev = NULL;
while (temp2 != NULL){
if (strcmp(temp2->type, temp->type) == 0 && strcmp(temp2->description, temp->description) == 0){
printf("Equipment already Exists ");
free(temp);
return list;
}
prev = temp2;
temp2 = temp2->next;
}
prev->next = temp;
}
return list;
}
Explanation / Answer
/**** I have modified the program . In youe program you have added only one condition when equipment is already present . I have added two more condition when Equipment type is smaller tthan the elements of the list and second is when equipment type is same but equipment description is smaller . I hope this function helps. ****/
struct equipment *append_to_list(struct equipment *list){
struct equipment *temp = (struct equipment *)malloc(sizeof(struct equipment));
printf(" Enter equipment type : ");
read_line(temp->type, NAME_LEN);
printf(" Enter description: ");
read_line(temp->description, NAME_LEN);
printf(" Please enter quantity: ");
scanf("%d",&temp->quantity);
temp->next = NULL;
if(list == NULL){
list = temp;
}
else{
struct equipment *temp2 = list, *prev = NULL;
while (temp2 != NULL){
// If the Equipment already present
if (strcmp(temp2->type, temp->type) == 0 && strcmp(temp2->description, temp->description) == 0){
printf("Equipment already Exists ");
free(temp);
return list;
}
// If the type is smaller
else if(strcmp(temp2->type, temp->type) > 0){
if(prev == NULL){
temp->next = temp2;
list = temp;
}
else{
prev->next= temp;
temp->next = temp2;
}
return list;
}
// If the type is same then ordering on the basis of description
else if(strcmp(temp2->type, temp->type) ==0 && strcmp(temp2->description, temp->description) > 0){
if(prev == NULL){
temp->next = temp2;
list = temp;
}
else{
prev->next= temp;
temp->next = temp2;
}
return list;
}
prev = temp2;
temp2 = temp2->next;
}
prev->next = temp;
}
return list;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.