【问题标题】:Doubly Linked List C++. Insert After Function not Working双向链表 C++。插入功能不起作用
【发布时间】: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-&gt;next == NULLtemp-&gt;next-&gt;prev = Node; 等原因退出循环。调用未定义行为,可能是SegFault。请尽快阅读About 页面并访问描述How to Ask a QuestionHow to create a Minimal, Complete, and Verifiable example (MCVE) 的链接。提供必要的详细信息,包括您的 MCVE、编译器警告和相关错误(如果有),将允许这里的每个人帮助您解决您的问题。
  • 我也添加了 temp != NULL 但仍然无法正常工作。@da
  • 请给出比“不工作”更详细的诊断。您是否在调试器中检查了生成的数据结构?哪些不变量被破坏了?你期待什么?你观察到什么?
  • (head == NULL) 是错误还是表明列表为空?如果 head 是第一个条目(如 while 循环中所示),则 head 必须在它为 NULL 时填写。如果新条目只有在找到afterWhat时才能插入,那么在没有找到的时候需要额外的检查才能失败。
  • 不要在 C++ 中使用malloc

标签: c++ doubly-linked-list


【解决方案1】:

next和prev节点的分配顺序错误

temp->next->prev = Node;
temp->next = Node;
Node->prev = temp;
Node->next = temp->next;

因为在第二行中有 temp->next=Node,然后是 Node->next=temp->next,结果是 Node->next=Node。像这样修复它

temp->next->prev = Node;
Node->prev = temp;
Node->next = temp->next;
temp->next = Node;// changed the position of this statement

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多