简体   繁体   English

在单链表中删除

[英]Deletion in singly linked list

I have this function deleteNode() for deleting a node from a linked list. 我有此函数deleteNode()用于从链表中删除节点。 This func. 这个功能。 is called in the main func. 在主函数中被称为。 like this deleteNode(&head, 10); 像这个deleteNode(&head, 10); , where head is the pointer to the first node of the linked list and 10 the value to be deleted. ,其中head是指向链表的第一个节点的指针,而10是要删除的值。

Here, the else if statement is commented and the function runs fine. 在这里, else if语句被注释,函数运行正常。 But when I uncomment the else if statement and run then the program crashes. 但是,当我取消注释else if语句并运行时,程序崩溃。 Why is it happening and what is the solution? 为什么会发生,解决方案是什么?

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

Because you're trying to access current->next->data without checking if the current->next is null first. 因为您尝试访问current->next->data而不先检查current->next是否为null。 You should modify your logic either to check if current->next != null before trying to access its data, or to check the current->data and remove it by saving the previous node also. 您应该修改逻辑,以在尝试访问其数据之前检查current->next != null是否current->next != null ,或者检查current->data并通过保存previous节点将其删除。

In your code you are trying to delete a single node from linked list with a given value, but since you are continuing the loop it will delete all the nodes with the given value after you fix the bug ie checking current->next != NULL before checking its data. 在您的代码中,您尝试从链表中删除具有给定值的单个节点,但是由于您继续循环,因此在修复错误(即检查current-> next!= NULL)后,它将删除具有给定值的所有节点在检查其数据之前。 You could refer to the following code to delete a single node. 您可以参考以下代码来删除单个节点。

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;
             free(current);
             return;

        }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM