c - 每当我尝试调用特定函数时出现分段错误



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

我已经搜索了类似的问题,解决方案说在我已经完成的标题处检查 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;
}

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

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

相关内容

  • 没有找到相关文章

最新更新