每当我尝试调用特定功能时都会出现细分错误

时间:2019-07-20 10:46:28

标签: c linked-list singly-linked-list

每当我尝试使用以下功能删除给定节点之后的节点时,都会出现分段错误

我一直在寻找类似的问题,解决方案说要在已经完成的标题中检查NULL

struct node *delete_aft(struct node *start)
{
    struct node *ptr,*nextptr;
    int x;
    printf("\nEnter the previous element of the element to be deleted ");
    scanf("%d",&x);
    ptr=start;
    ptr->next=nextptr;
    while(ptr!=NULL&&ptr->next!=NULL)
    {
        if(ptr->data==x)
        {
            ptr->next=nextptr->next;
            free(nextptr);
            goto exit;
        }
        else
        {
            ptr=nextptr;
            nextptr=nextptr->next;
        }
    }
    if(ptr->next==NULL)
    printf("\n Element not found");
    exit:return start;
}

1 个答案:

答案 0 :(得分:0)

我注释了我进行更改的代码。

struct node *delete_aft(struct node *start)
{
    struct node *ptr,*nextptr;
    int x;
    printf("\nEnter the previous element of the element to be deleted ");
    scanf("%d",&x);
    ptr = start;
    while (ptr != NULL && ptr->next != NULL)
    {
        if (ptr->data == x)
        {
            // Make temporary copy of ptr->next.
            nextptr = ptr->next;
            // Set ptr->next to the node after ptr->next, i.e. ptr->next->next.
            ptr->next = nextptr->next;
            free(nextptr);
            goto exit;
        }
        else
        {
            // Search the next node.
            ptr = ptr->next;
        }
    }
    // If we reach this point, then x was not found, or x was the last node.
    if(ptr->next == NULL)
        printf("\n Element not found");
    exit:return start;
}