Home > Software engineering >  Checking if there is nothing in the list to be removed
Checking if there is nothing in the list to be removed

Time:03-13

I have written the below function for removing nodes from a list:

int remove_node_in_list( Node **set, size_t pos, Node **head )
{
 if( *head == NULL ){
    printf("LIST IS EMPTY\n");
 }

 int success = set[pos] != NULL;

 if ( success )
 {
    Node *tmp = set[pos];
    set[pos] = set[pos]->next;
    free(tmp);
 }

 return success;
}

But, I think that the check if my list is empty does not work right. I just want to check if my list is empty in order to print a message for it and nothing to be removed so.

CodePudding user response:

You should put a return inside the if that checks if the list is empty, if the list is empty, then there should be no further processing of the function. It would be up to you how you want to handle that "error" when calling that function, something like:

   int remove_node_in_list( Node **set, size_t pos, Node **head )
    {
     if( *head == NULL )
        return -1;
    
     int success = set[pos] != NULL;
    
     if ( success )
     {
        Node *tmp = set[pos];
        set[pos] = set[pos]->next;
        free(tmp);
     }
    
     return success;
    }
    

 /* Inside main */
 response = remove_node_in_list(args);
        
 if (response == -1)
     printf("List is empty");
  • Related