我正在尝试使用链表进行插入排序,但这段代码似乎有运行时错误。
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/