c++ - 插入排序中的运行时错误

标签 c++ runtime-error insertion-sort

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

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 block 中。

你正在遍历列表,一切似乎都很好......但是如果你到达列表的末尾并且 current->data 仍然小于或等于 数据??呃哦! current = current->link,current 现在将为 NULL,因此下一个 current->data 将尝试取消引用空指针!

只需在你的循环条件中添加一个检查,一切都会变得完美:

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

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

关于c++ - 插入排序中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149512/

相关文章:

java - ArrayLinkedList 插入排序

c++ - 如何使 Python 运行时安全?

error-handling - 如何将 libxml2 xmlParserErrors 代码转换为可打印字符串?

c++ - 使用 vector 迭代器时出现运行时错误

java - 优先级队列插入排序

java - 使用 System.nanoTime() 对不同长度的插入排序进行计时

C++:找不到静态链接

c++ - 将文档添加到 Lucene 索引会导致崩溃

c++ - CORBA::短值检查

c# - SignTool 错误 : Access is denied