gpt4 book ai didi

c++ - 是否可以将新的 ListNode 分配给链表的现有节点?

转载 作者:行者123 更新时间:2023-11-28 05:13:46 28 4
gpt4 key购买 nike

我正在编写一个函数,在与 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 的下一个,但它产生相同的结果。有谁知道发生核心转储的位置吗?

最佳答案

你的代码有很多问题,我不调试也能看出来。请发布测试用例+错误+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;
}

关于c++ - 是否可以将新的 ListNode 分配给链表的现有节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43069752/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com