8.4. Example - Linked Lists

8.4.1. Append To a List

typedef struct list {
    int data;
    struct list *next;
} LIST;


LIST *append( LIST *start, int newdata )
{
    LIST *new, *end, *ret;

    if( (new = (LIST *)malloc(sizeof(LIST))) == NULL) {
        fprintf( stderr, "Memory Allocation error.\n" );
        return 1;
    }
    if( start == NULL )
        ret = new;
    else {
        ret = start;
        end = start;
        while( end->next != NULL ) end = end->next;
        end->next = new;
    }
    new->data = newdata;
    new->next = NULL;
    return( ret );
}

8.4.2. Delete From a List

LIST *remove( LIST *start, LIST *remove )
{
    LIST *previous, *ret;

    if( remove == NULL || start == NULL ) return( NULL );
    if( remove == start ) {
        ret = remove->next;
        free( remove );
        return( ret );
    }
    previous = start;
    while( previous->next != remove && previous->next != NULL )
        previous = previous->next;
    if( previous->next != NULL ) { /* item found in list */
        previous->next = remove->next;
        free( remove );
    }
    return( start );
}

8.4.3. Sorted Insert To a List

LIST *insert( LIST *start, int newdata )
{
    LIST *new, *next, *previous, *ret;

    if( (new = (LIST *)malloc(sizeof(LIST))) == NULL) {
        fprintf( stderr, "Memory Allocation error.\n" );
        return 1;
    }
    if( start == NULL ) {
        ret = new;
        new->next = NULL;
    }
    else {
        next = start;
        previous = NULL;
        while( next->data < newdata && next != NULL ) {
            previous = next;
            next = next->next;
        }
        new->next = next;
        if( previous == NULL )
            ret = new;
        else {
            previous->next = new;
            ret = start;
        }
    }
    new->data = newdata;
    return( ret );
}