从链表中删除

时间:2018-10-13 10:22:20

标签: c

我需要从链接列表中删除一个项目。

我愿意从头开始,将标题(称为carbase)重定向到列表中的下一个。

当我运行该函数时,它确实释放了结构的数据。但是,指针没有移动。

struct carinfo_t *removeCarinfo(struct carinfo_t *carbase, char *merk, char 
*model, int year){
struct carinfo_t *curr = carbase;
while(curr != NULL){
int a, b, c;
a = strcmp(curr->brand, merk);
b = strcmp(curr->model, model);
c = curr->year;
if (a == 0 && b == 0 && c == year){ //verwijderen wanneer dit waar is
    if(curr = carbase) //als het de eerste in de lijst is
    carbase = carbase->next;
    freeCarinfo(curr);
    return carbase;

}
curr = curr->next;
}

}

2 个答案:

答案 0 :(得分:0)

使用这种方法:

void deleteList(struct Node** head_ref) 
{ 
   /* deref head_ref to get the real head */
   struct Node* current = *head_ref; 
   struct Node* next; 

   while (current != NULL)  
   { 
       next = current->next; 
       free(current); 
       current = next; 
   } 

   /* deref head_ref to affect the real head back 
  in the caller. */
   *head_ref = NULL; 
} 

您只需要在此处传递头Node引用。

答案 1 :(得分:0)

尝试将“ carbase”指针作为结构的头部单元格传递,然后尝试以下操作:

struct carinfo_t *removeCarinfo(struct carinfo_t *carbase, char *merk, char*model, int year){
struct carinfo_t *curr = carbase;
while(curr->next != NULL){
    int a, b, c;
    a = strcmp(curr->next->brand, merk);
    b = strcmp(curr->next->model, model);
    c = curr->next->year;
    if (!a && !b && c == year){
        struct carinfo_t *aux = curr->next;
        curr->next = curr->next->next;
        free(aux);
}
curr = curr->next;

}