Search code examples
cpointersdata-structureslinked-listabstract-data-type

insert_last function in linked list


I don't really know what's wrong here. I keep getting SIGSEGV. I have debugged and I saw the line where it's crashing, it is this one: (*last)->next = p; . In case you need all the function:

void insert_last(NodeT** first, NodeT** last, int givenKey)
{
    NodeT *p = malloc(sizeof(NodeT));
    p->key = givenKey;
    p->next = NULL;
    if(*first == NULL)
        *first = p;
    else
    {
        (*last)->next = p;
        *last = p;
    }
}

And this is the main:

int main()
{
    NodeT *first, *last;
    first = last = NULL;
//    insert_first(&first,&last,5);
//    insert_first(&first,&last,3);
    insert_last(&first,&last,2);
    NodeT *p = first;
    while(p != NULL)
    {
        printf("%d ",p->key);
        p = p->next;
    }
}

Solution

  • You forgot to set last in the *first == NULL case.

    void insert_last(NodeT** first, NodeT** last, int givenKey)
    {
        NodeT *p = malloc(sizeof(NodeT));
        p->key = givenKey;
        p->next = NULL;
        if(*first == NULL)
        { // add this
            *first = p;
            *last = p; // add this
        } // add this
        else
        {
            (*last)->next = p;
            *last = p;
        }
    }