1
votes

Trying to understand how to properly setup a function that will delete from a linked list based on a user specified parameter. So I have a global variable entitled list that holds all the dog structs within them. I can get the list to delete the node the user wants removed if there are multiple structs in the linked list, for some reason though if there is only one node or the node I want deleted is the head of the list the function does not remove it. Any direction for this issue would be greatly appreciated.

void remove_one(char* name)
{


    struct dog *tempList = list;
    struct dog *previous = NULL;

    if (tempList == NULL) {
        return;
    }

    while (tempList != NULL) {
        if (strcmpi(tempList->name, name) == 0) {


            if (previous == NULL) {
                tempList = tempList->next;
            }  


            else {
                previous->next = tempList->next;
                free(tempList);
                tempList = previous->next;
            }

            return;
        }

        else {
            previous = tempList;
            tempList = tempList->next;
        }


    }

    return;

}
1

1 Answers

1
votes

2 problems here:

if (previous == NULL) {
      tempList = tempList->next;
          }  

First, tempList is a local variable, so you don't really delete the head. Next time you enter in the routine, list is still pointing to the same (valid) value.

Second, you don't free the memory.

correct code:

if (previous == NULL) {
      list = tempList->next;  // change global variable so head is "tempList->next"
      free(tempList);  // free templist memory else you get memory leak
          }