Home > front end >  Modify my appending function to be able to append for an empty list as well
Modify my appending function to be able to append for an empty list as well

Time:11-25

How should I modify this function to be able to append from an existing list to a NULL/empty list?

void Appending(Diary *List, Diary *Element) {
    Diary *moving = List;
    if (List == NULL) {
        List = kovetkezo;
    } else { 
        while (moving->NextDiary != NULL)
            moving = moving->NextDiary;
        moving->Nextdiary = Element;
    }
}

CodePudding user response:

To allow appending to an empty list, the list pointer in the caller must be updated.

You must either take a pointer to the List pointer: Appending(&head, element);

// Taking a double pointer to the initial element:
void Appending(Diary **List, Diary *Element) {
    Diary *moving = *List;
    if (moving == NULL) {
        *List = Element;
    } else { 
        while (moving->NextDiary != NULL)
            moving = moving->NextDiary;
        moving->Nextdiary = Element;
    }
}

or you can return the updated List pointer and update the list pointer in the caller by storing the return value into it: head = Appending(head, element);

// Returning an updated pointer to the initial element:
Diary *Appending(Diary *List, Diary *Element) {
    Diary *moving = List;
    if (moving == NULL) {
        List = Element;
    } else { 
        while (moving->NextDiary != NULL)
            moving = moving->NextDiary;
        moving->Nextdiary = Element;
    }
    return List;
}

CodePudding user response:

Declare the function to return the updated list.

Diary* Appending(Diary* List, Diary* Element)
{
    Diary* moving = List;
    if (List == NULL)
    {
        List = kovetkezo;
    }
    else
    { 
        while (moving->NextDiary != NULL)
            moving = moving -> NextDiary;
        moving->Nextdiary = Element;
    }
    return List;
}

The caller then uses:

list = Appending(list, newElement);
  •  Tags:  
  • c
  • Related