在链表中获取分段错误

时间:2016-10-07 09:00:07

标签: c linked-list segmentation-fault

使用此代码删除处理列表开始时创建的重复值 但是在使用此代码时因段失败而收到错误,否则程序运行良好。

void remove_duplicate(){
    q = start;           //list start has already been created
    while(q->next){
        q=q->next;
        if(q->id==q->next->id){    //removing duplicate values
            q->next->prev = q->prev;
            q->prev->next = q->next;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

如果你是列表中倒数第二个节点,q->next->next是空指针,那么你进入循环体(因为q->next不是NULL )并直接使q指向最后一个节点。因此,当您下次使用q->next时,您将取消引用NULL指针并具有未定义的行为

更改语句的顺序,并将q = q->next作业放在最后。

或者改为使用for循环:

for (q = start; q->next != NULL; q = q->next){
    if ...
}

答案 1 :(得分:1)

你的问题可能在于这一行,你断言q->next元素存在:

while(q->next)

现在您将链中的下一个元素分配给q,

q=q->next;

现在您的q->next可能是NULL

if(q->id==q->next->id)

q=q->next;区块下移动if

void remove_duplicate(){

  q = start->next;    
  if (q==NULL)
  return -1;      
  while(q->next){

    if(q->id==q->next->id){                
        q->next->prev = q->prev;
        q->prev->next = q->next;
    }
    q=q->next;
  }
}

答案 2 :(得分:0)

void remove duplicate()
{
   q=start;

   while(q->next!=NULL)
   {
      if(q->id==q->next->id)
      {
         q->next=q->next->next; 
      }

      q=q->next;
   }
}

它可以帮助你。

相关问题