【问题标题】:Deleting a node in a sorted linked list in C在C中删除排序链表中的节点
【发布时间】:2013-08-17 04:13:28
【问题描述】:

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

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

Click here 获取完整程序。提前致谢!

【问题讨论】:

    标签: c sorting linked-list logic


    【解决方案1】:

    您的while 循环一直执行到help_ptr->next 为NULL。在循环之后,您比较 help_ptr->next->data - 但由于 help_ptr->next 是 NULL,它会崩溃。

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

    【讨论】:

    • 感谢您的快速回复!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2016-01-02
      • 2016-03-02
      • 1970-01-01
      • 2014-08-15
      • 2022-01-08
      • 2017-10-21
      • 2013-08-30
      相关资源
      最近更新 更多