0
Can someone explain to me with this code at the switch statement? Anything improvement in my linked list deletion code?
void delete_report() { printf("\n ___ Deleting a Fault Report ___ \n\n"); printf("Enter the Fault ID to delete: "); scanf("%d", &element); if (list == NULL) printf("List is empty\n"); else if (element == list->faultid) list = list->next; else { temp = list; while (temp->faultid != element && temp->next!= NULL) { prev = temp; temp = temp->next; } if (temp->next != NULL) { prev->next = prev->next->next; free(temp); } printf("Fault ID not found"); return; } printf("Fault Report %d has been deleted \n", element); }
2 Réponses
+ 1
Your delete code fails, if you attempt to delete the last element as temp->next will be null. Change if (temp->next != NULL) to if (temp->faultid == element).
prev->next = prev->next->next; can be simplified to prev->next = temp->next;
You always print failure message and return. It should be on else.
0
Please put the code in the playgound. Copy the link and paste it here. I see no switch statement so likely your code got truncated.