Search code examples
cpointerslinked-listsingly-linked-listfunction-definition

Deleting a node from a simle linked list


If I have these structs:

typedef struct item 
{
type data;
struct item *next;
} Item;
typedef struct list 
{
Item *head;
} List;

And a pointer to a node which I want to delete : Item * toDelete, which belongs to the list List lst, Can I use the following function to delete the node?:

void delete(Item * toDelete, List * lst){
   Item * tmp=lst->head;
   while (tmp->next!=toDelete){
       tmp=tmp->next;
   }
   tmp->next=toDelete->next;
   free(toDelete);
}

Or in other words, is it legal to compare between two pointers of structs?


Solution

  • For starters this function

    void delete(Item * toDelete, List * lst){
       Item * tmp=lst->head;
       while (tmp->next!=toDelete){
           tmp=tmp->next;
       }
       tmp->next=toDelete->next;
       free(toDelete);
    }
    

    can invoke undefined behavior because in the while loop there is no check whether tmp is equal to NULL. Secondly the function ignores the case when the node to be deleted is equal to the head node.

    The function can be defined the following way

    int delete( Item *toDelete, List *lst )
    {
        Item **current = &lst->head;
    
        while ( *current && *current != toDelete )
        {
            current = &( *current )->next;
        }
    
        int success = *current != NULL;
    
        if ( success )
        {
            *current = ( *current )->next;
            free( toDelete );
        }
    
        return success;
    }