插入排序中出现运行时错误
Runtime error in 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块中
你正在循环浏览列表,一切似乎都很好。。。但是,如果你到达列表的末尾,并且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;
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 字符串::插入产生运行时错误
- 对双向链表进行排序会产生运行时错误
- 合并排序的C 实现的运行时错误
- 自定义char*插入功能多次运行时会产生运行时错误
- 在运行时C++将元素插入到向量中.引发运行时错误
- 为什么我在C++中的类中插入值时出现运行时错误
- 为什么在为数组输入并输入合并排序函数后出现运行时错误
- 在先前在 BST 中删除节点后尝试插入时出现运行时错误
- 合并两个排序列表出现运行时错误
- 快速排序实现C++运行时错误
- 使用自定义比较器排序时出现运行时错误
- 插入排序中出现运行时错误