/* Removes a product given the name of such product. */ void removeProduct(char * productName) { struct product *pProductToDelete = NULL; pProductToDelete = searchForProduct(productName); if (pProductToDelete != NULL) { // product to delete was found printf("%s Was Deleted\n\n", productName); if (pProductToDelete == pFirstNode) { // If deleting what turned out to be the first element pFirstNode = pProductToDelete->next; // remove it from the list by moving this reference } else { // By keeping a reference to the product before the one we're deleting // we can delete the reference to it. // This variable was designated a value inside searchForProduct() pProductBeforeProductToDelete->next = pProductToDelete->next; } free(pProductToDelete); } else { printf("%s was not found!", productName); // Product not found } }
int main() { inputData(); inputData(); inputData(); outputData(); printf("Searching for product ... \n"); searchForProduct("Tomato"); printf("Removing a product ...\n"); removeProduct("Tomato"); printf("The remaining products are: \n"); outputData(); return 0; }
void removeProduct(char * productName){ struct product *pProductToDelete = NULL; pProductToDelete = searchForProduct(productName); if(pProductToDelete != NULL){ printf("%s was deleted\n\n", productName); // And if this product is the first product in our list // and we want it to delete we must define the next product in the list // to the first node. if(pProductToDelete == pFirstNode){ pFirstNode = pProductToDelete->next; } else { // We need to got pProductToDelete and assigned it next to the product // that before the product is deleted pProductBeforeProductToDelete->next = pProductToDelete->next; } free(pProductToDelete); } else { // If we did not find a product printf("%s was not found", productName); } }