Search code examples
cstructlinked-listtail

Remove a node at the tail of a linked list C


I wrote code to remove the node at the tail of a linked list. The code works properly in different testcases, but I think I made my code a bit cumbersome. However, I don't see what I can do differently?

node_t *remove_t (node_t *l){
if (l==NULL){
    return l;
}
else {
    node_t *curr=l;
    node_t *ret=l;
    if (curr->next==NULL){
        l=NULL;
        return l;
    }
    else {
        while (curr->next->next!=NULL){
            curr=curr->next;
        }
        curr->next=NULL;
        free(curr->next);
        return ret;
    }
}
}

Solution

  • I'm not sure that you can change the logic much - as your approach of 3 different cases (empty list, list with 1 item, and list with >1 items) is reasonable. You can format the code for easier reading: Something like:

    node_t *remove_t (node_t *l){
        // case 1: Empty list
        if (l==NULL){
            return l;
        } ;
    
        // case 2: List with one item. Return empty list.
        node_t *curr=l;
        if (curr->next==NULL){
            // Remember to free this element.
            free(curr) ;
            l=NULL;
            return l;
        } ;
    
        // case 3: list > one item
        // Move curr to last item
        while (curr->next->next!=NULL){
            curr=curr->next;
        }
        // Note order of free/null setting.
        free(curr->next);
        curr->next=NULL;
    
        return l;
    }