是否可以将新的列表节点分配给链表的现有节点
Is it possible to assign a new ListNode to an already existing node of a linkedlist?
我正在编写一个函数,该函数在与head1
关联的列表中出现变量位置后输入与head2
关联的链表。但是,我不断得到一个核心转储:
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
旁边,但它会产生相同的结果。有没有人知道核心转储发生在哪里?
你的代码有很多问题,即使没有调试,我也可以看到。请发布测试用例 + 错误 + 列表节点定义。
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;
}
相关文章:
- 预分配的节点向量中的无锁树节点分配
- 如何在 C++11 的内存池中分配 std::map 的内部RB_tree节点?
- nullptr = 节点分配不正确
- C++错误(从不兼容的类型"void"分配给树节点*)
- 根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?
- 将节点添加到链接列表中,而无需明确分配内存空间(无需使用新)
- 是否可以将新的列表节点分配给链表的现有节点
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- 将指针分配给链接列表节点会引发"Segmentation Fault"
- 如何从链表上的节点为分配的类释放内存
- 如何在速推中为节点分配标签
- 用C++在树中分配节点指针
- 关于在omnetpp.ini中将两个不同的应用程序随机分配到50个节点
- 分段 C++中链表节点分配的错误
- 我们需要为链表节点分配内存吗
- 为节点分配指针地址
- 将子节点分配给父节点
- 在C/ c++中,链表只有头指针分配在堆栈中,其他节点分配在堆中.这可能导致内存泄漏
- 为链表中的节点分配内存,但出乎意料的是,它内部的下一个节点也被分配了
- 使用pugixml将节点分配给新的父节点