Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Re-write add so that it adds in alphabetical order. Do not add a name if it alre

ID: 3706308 • Letter: R

Question

Re-write add so that it adds in alphabetical order. Do not add a name if it already exists in the list. That is, before adding, traverse the list to make sure the name is not already there. Print an error message if it exists.

Explanation / Answer

Person *add(Person *ptr, char *n, int a) { Person *newNode = malloc( sizeof(Person) ); newNode->name = malloc( strlen(n) + 1 ); strcpy(newNode->name, n); newNode->age = a; newNode->next = ptr; if(ptr == NULL) { return newNode; } else if(strcmp(n, ptr->name) < 0) { newNode->next = ptr; return newNode; } else { Person *temp = ptr; while(temp->next != NULL) { if(strcmp(n, temp->next->name) < 0) { newNode->next = temp->next; temp->next = newNode; return ptr; } temp = temp->next; } temp->next = newNode; return ptr; } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote