1

所以我写了一个插入、删除和显示排序链表的程序。一切运行顺利,但是当我输入一个无效的数字(不在排序链表中)进行删除时,我的程序崩溃了。这是我的删除功能:-

struct node* remove(struct node* head_ptr, int target)
{
    struct node* help_ptr, *node2del;
    help_ptr = head_ptr;
    if(help_ptr != NULL)
    {
        if(help_ptr -> data == target)
        {
            head_ptr = help_ptr -> next;
            free(help_ptr);
            return head_ptr;
        }
        while (help_ptr -> next != NULL)
        {
            if(help_ptr -> next -> data == target)
            {
                node2del = help_ptr -> next;
                help_ptr -> next = help_ptr -> next -> next;
                free(node2del);
                return head_ptr;
            }
            help_ptr = help_ptr -> next;
        }
        if(help_ptr->next->data != target)
            printf("\n%d is not in the list.",target);
    }
    return head_ptr;
}

点击这里查看完整程序。提前致谢!

4

2 回答 2

3

您的while循环执行直到help_ptr->nextis NULL。在循环之后,您进行比较help_ptr->next->data- 但按原样help_ptr->nextNULL它会崩溃。

最后一个if基本上是不必要的。如果在循环期间未找到while该项目,则该项目不在列表中。

于 2013-08-17T04:16:13.133 回答
0

遍历整个列表后(就像您使用 while 循环所做的那样),您将再次检查“if 条件”中肯定会导致分段错误的下一个元素。如果您正在搜索的元素是,则在退出 while 循环后未找到欢迎您说“未找到元素”。

于 2013-08-17T06:28:33.730 回答