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

时间:2015-04-20 02:06:38

标签: c linked-list segmentation-fault

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则不行。

1 个答案:

答案 0 :(得分:0)

使用添加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。将其分配给current后,current为NULL。