【发布时间】:2020-10-08 07:43:36
【问题描述】:
我写了一个 insertAfter 函数,但它不起作用 请帮忙!!!
该功能不起作用。当我运行它时测试失败。
template <class T>
void LinkedList<T>::insertAfter(T toInsert, T afterWhat)
{
ListItem<T> *Node = (ListItem<T>*)malloc(sizeof(ListItem<T>));
Node->value = toInsert;
Node->next = NULL;
Node->prev = NULL;
if(head == NULL){
return;
}
ListItem<T> *temp = head;
while(temp->value != afterWhat && temp->next != NULL){
temp = temp->next;
}
temp->next->prev = Node;
temp->next = Node;
Node->prev = temp;
Node->next = temp->next;
}
【问题讨论】:
-
如果由于
temp->next == NULL、temp->next->prev = Node;等原因退出循环。调用未定义行为,可能是SegFault。请尽快阅读About 页面并访问描述How to Ask a Question 和How to create a Minimal, Complete, and Verifiable example (MCVE) 的链接。提供必要的详细信息,包括您的 MCVE、编译器警告和相关错误(如果有),将允许这里的每个人帮助您解决您的问题。 -
我也添加了 temp != NULL 但仍然无法正常工作。@da
-
请给出比“不工作”更详细的诊断。您是否在调试器中检查了生成的数据结构?哪些不变量被破坏了?你期待什么?你观察到什么?
-
(head == NULL) 是错误还是表明列表为空?如果 head 是第一个条目(如 while 循环中所示),则 head 必须在它为 NULL 时填写。如果新条目只有在找到afterWhat时才能插入,那么在没有找到的时候需要额外的检查才能失败。
-
不要在 C++ 中使用
malloc。