为什么此代码在链表的末尾插入节点会导致分段错误

时间:2020-03-12 14:10:55

标签: c data-structures linked-list clang

我正在尝试实现链表功能以将节点添加到列表的末尾,但它几乎触发了每一行的分段错误。

SinglyLinkedListNode * insertNodeAtTail(SinglyLinkedListNode * head,int Data){

SinglyLinkedListNode* Node;
Node = malloc(sizeof(SinglyLinkedListNode));

SinglyLinkedListNode* current; 
current = head;


Node->data = Data;
Node->next = NULL;

if( head->next == NULL)     /* 0 element llist*/
{
    head = Node;
}
else
{
    //current = head;
    /*
            while(current->next != NULL) 
    */
    while(current->next != NULL)
    {
        current = current->next;
    }  // exit when current->next = lastNode->next = NULL
    current->next = Node;

}

1 个答案:

答案 0 :(得分:0)

这可能会导致段错误:

while(current->next != NULL)  /* if current is NULL 
dereferencing it will cause segfault. */