Adding (appending) a new item to our list
When adding (appending) new items to our list,
we need to be careful about the special (edge) cases:
- the empty list, and
- when adding items to the end:
void append_item(char *newstring)
{
if(list == NULL) { // append to an empty list
list = malloc( sizeof(LISTITEM) );
if(list == NULL) {
perror( __func__ );
exit(EXIT_FAILURE);
}
list->string = strdup(newstring);
list->next = NULL;
}
else { // append to an existing list
LISTITEM *p = list;
while(p->next != NULL) { // walk to the end of the list
p = p->next;
}
p->next = malloc( sizeof(LISTITEM) );
if(p->next == NULL) {
perror( __func__ );
exit(EXIT_FAILURE);
}
p = p->next; // append after the last item
p->string = strdup(newstring);
p->next = NULL;
}
}
|
Notice how we needed to traverse the whole list to locate its end.
Such traversal can become expensive (in time) for very long lists.
CITS2002 Systems Programming, Lecture 19, p10, 3rd October 2023.
|