插入排序中出现运行时错误

Runtime error in insertion sort

本文关键字:运行时错误 插入排序      更新时间:2023-10-16

我试图使用链表进行插入排序,但这段代码似乎有运行时错误。

void Insert(int data)
{
    node* temp=new node();
    temp->data=data;
    temp->link=NULL;
    if(head==NULL)
    {
        head=temp;
        return;
    }
    node* current=head;
    if(current->data>data)
    {
        temp->link=head;
        head=temp;
        return;
    }
    else
    {
        current=head;
        node* trail=head;
        while(current->data<=data)
        {
            trail=current;
            current=current->link;
        }
        trail->link=temp;
        temp->link=current;
    }
}

您的问题在第二个if.的else块中

你正在循环浏览列表,一切似乎都很好。。。但是,如果你到达列表的末尾,并且current->data仍然小于或等于data,会发生什么??哦!current = current->link,当前为NULL,因此下一个current->data将尝试取消引用空指针!

只要在你的循环条件中添加一个检查,一切都会很好:

while(current && current->data <= data) {

如果current是空指针,则此表达式现在将短路,从而避免出现该问题。

不确定这是否是唯一的错误,但:

    current=head;
    node* trail=head;
    while(current->data<=data) // <-- This doesn't check if current->link is NULL
    {
        trail=current;
        current=current->link; /// <-- If current is NULL this would explode
    }
    trail->link=temp;
    temp->link=current;