Deleting a node from linked list in C

前端 未结 6 1968
醉酒成梦
醉酒成梦 2020-12-07 04:05

My problem is deleting a node from linked list.

I have two structs :

typedef struct inner_list 
{
 int count;
 char word[100];
 inner_list*next;
}          


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-07 04:37

    There's a big problem in that if you end up needing to delete the first element of the outer list, you never pass back the new head of the list. Your origuinal code needs changing as follows (also put in all the other good suggestions):

    void delnode(outer_list **tbd,char num[100]) // pass a pointer to tbd
    {
        outer_list *temp, *m;
        temp = *tbd;
        while(temp!=NULL)
        {
            if(strcmp(temp->word,num)==0)
            {
                if(temp==*tbd)
                {
                    // Delete the inner list here
                    *tbd=temp->next;
                    free(temp);
                    return;
                }
         // rest of function
    

    You'd call it like this:

    outer_list* myList;
    
    // lots of code including initialising and adding stuff to the list
    
    delnode(&mylist, wordtoDelete);  // note the '&' sign
    

提交回复
热议问题