将节点添加到链表时出现分段错误

MS535
Node *orderedInsert(Node *p, int newval)
/* Allocates a new Node with data value newval
   and inserts into the ordered list with 
   first node pointer p in such a way that the
   data values in the modified list are in 
   ascending order as the list is traversed.
*/
{
   Node* current = NULL;
   Node* prev = NULL;
   Node* newNode = (Node*)malloc(sizeof(Node));
   newNode->next = NULL;
   newNode->data = newval;

   if(newNode == NULL)
      printf("Could not allocate memory for new node");

   current = p;   

   if(p == NULL){

      p = newNode;
      newNode->next = NULL;
      newNode->data = newval;
      return  p;
   }
   else if(newval < p->data){
      newNode->next = p;
      p = newNode;
      return p;
   }
   else{ 
      prev = p;
      current = current->next; 



      while(newNode->data > current->data && current != NULL){

         prev = current;
         current = current->next;
      }
      if(prev->next == NULL){//the error is located somewhere here I think
         prev->next = newNode;
         newNode->data = newval;
         newNode->next = NULL;
         return p;   
      }
      else{
         newNode->next = current;
         prev->next = newNode;
         return p;
      }
   }   
}

添加大于任何其他节点的节点(这将在列表的末尾)时,我只会遇到分段错误错误。如果我按4 3 2 1或4 2 1 3的顺序输入它们会很好,但如果我输入1 2则不能。

ycshao

以您将1和2相加的示例为例。

第一次迭代将击中

if(p == NULL){
  p = newNode;
  newNode->next = NULL;
  newNode->data = newval;
  return  p;
}

然后下一个指针指向NULL。

然后,当您添加2时,将命中:

else{ 
  prev = p;
  current = current->next; 

  while(newNode->data > current->data && current != NULL){
    ...
  }

current->next是NULL。将其分配给后currentcurrent为NULL。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将头节点添加到单链表中会产生分段错误错误

释放链表节点时出现分段错误

我得到一个分段错误尝试的节点添加到链表在C结束时(核心转储)错误++

为什么将项目添加到链表会导致分段错误?

尝试将新节点添加到链接列表时,为什么会出现细分错误?

符石将节点添加到有序链表 - 错误

将节点添加到链表的开头会导致错误消息,我不关注

将节点添加到C中的链表时,EXC_BAD访问

SEGV:将节点添加到链表的末尾时,大小为8的invalig写

将Firebase添加到Flutter时出现GradGrad错误

将AFNetworking添加到新项目时出现错误

添加到排序的链表时,如何避免出现段错误?

将元素添加到已排序的链表C ++中时出现的问题

malloc链表时出现分段错误

遍历链表时出现分段错误

递归打印链表时出现分段错误

将项目添加到链表段错误的末尾

如何将链表添加到链表的特定节点上?

在链表中附加节点-为什么会出现分段错误?

添加到单个链表的末尾分段故障C

将项目添加到“使用...结束时”时出现Excel错误91

尝试连接节点时出现分段错误

使用节点结构时出现分段错误

将元素添加到链表

将CER转换为PFX时出现强制错误(用于添加到Azure门户)

将累加器逻辑添加到Web服务请求时出现XSLT错误

尝试通过状态将类添加到列表项元素时出现解析错误

将预处理层添加到顺序模型时出现 Keras 错误

将 navigation.navigate 添加到组件时出现“错误:未定义不是对象”?