insert_last链表中的函数

insert_last function in linked list

我真的不知道这里出了什么问题。我不断收到 SIGSEGV。我已经调试过了,我看到了它崩溃的那一行,就是这一行: (*last)->next = p; 。如果您需要所有功能:

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;
    }
}

这是主要的:

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;
    }
}

您忘记在 *first == NULL 的情况下设置 last

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;
    }
}