我正在编写一个函数,在与head2
关联的列表中发生变量位置后,输入与head1
关联的链接列表。但是,我一直在获得核心转储:
void mergeLists(ListNode *head1, ListNode *head2, const int &location){
ListNode *tail1, *tail2, *run;
tail1=head1;
tail2=head2;
if(head1->pointer_Next!=nullptr){
while(tail1->content!=location){
tail1=tail1->pointer_Next;
}
if(head2->pointer_Next!=nullptr){
while(tail2->pointer_Next!=nullptr){
run=tail1->pointer_Next;
tail1->pointer_Next=new ListNode;
tail1=tail1->pointer_Next;
tail1->content=tail2->content;
tail1->pointer_Next=run;
tail2=tail2->pointer_Next;
}
}
}
delete tail1;
delete tail2;
delete run;
}
第12行的操作是否有违法行为?我是通过GDB运行的,我很确定这就是问题所在。我已经尝试将指针设置为nullptr
旁边但它产生相同的结果。有没有人知道核心转储在哪里发生?
答案 0 :(得分:1)
您的代码存在很多问题,即使没有调试也能看到。请发布测试用例+错误+ ListNode定义。
void mergeLists(ListNode *head1, ListNode *head2, const int &location){
ListNode *tail1, *tail2, *run;
tail1=head1;
tail2=head2;
if(head1->pointer_Next!=nullptr){ <------ What if head1 is nullptr ?
while(tail1->content!=location){ <---- What if tail1 is nullptr ?
tail1=tail1->pointer_Next; <---- What if tail1->pointer_Next is nullptr ?
}
if(head2->pointer_Next!=nullptr){ <--- What if head2 is nullptr ?
while(tail2->pointer_Next!=nullptr){ <--- What if tail2 is nullptr ?
run=tail1->pointer_Next;
tail1->pointer_Next=new ListNode;
tail1=tail1->pointer_Next;
tail1->content=tail2->content;
tail1->pointer_Next=run;
tail2=tail2->pointer_Next;
}
}
}
delete tail1; <---- Why do you delete tail1 , which is Node in the list
delete tail2; <---- Why do you delete tail2 , which is Node in the list
delete run;
}