删除单链表

时间:2016-03-26 14:10:10

标签: c data-structures linked-list

我有这个函数deleteNode()用于从链表中删除节点。这个功能。在主函数中调用。像这样deleteNode(&head, 10);,其中head是指向链表第一个节点的指针,10是要删除的值。

这里,else if语句被注释,函数运行正常。但是,当我取消注释else if语句并运行时,程序崩溃了。为什么会这样?解决方案是什么?

void deleteNode(node **h, int value)
{
    node *current, *temp;
    current = *h;

    while(current != NULL)
    {
        // if the node to be deleted is the first node of the list
        if(current == *h && current->data == value)    
        {
            *h = current->next;
        }
        /*
        // if the node to be deleted is other than first node
        else if(current->next->data == value)
        {
            temp = current->next;
            current->next = temp->next;
            free(temp);
        } */
        current = current->next;
    }                  
}

2 个答案:

答案 0 :(得分:1)

因为您尝试访问current->next->data而未检查current->next是否为空。您应该修改逻辑,以便在尝试访问其数据之前检查current->next != null,或检查current->data并通过保存previous节点将其删除。

答案 1 :(得分:1)

在您的代码中,您尝试使用给定值从链接列表中删除单个节点,但由于您继续循环,因此在修复错误后将删除具有给定值的所有节点,即检查当前 - >> next!= NULL ,然后再检查其数据。您可以参考以下代码删除单个节点。

{{1}}