是否可以将新的列表节点分配给链表的现有节点

Is it possible to assign a new ListNode to an already existing node of a linkedlist?

本文关键字:节点 分配 链表 列表 是否      更新时间:2023-10-16

我正在编写一个函数,该函数在与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;
}