无法从单个链接列表中删除

时间:2016-07-05 10:53:01

标签: c linked-list singly-linked-list

所以我有struct

struct Book {
    char *title;
    char *author;
    int  pages;
    struct Book *next;
}*start=NULL;

我有以下用于删除的功能:

void delete(int x) {
    struct Book *current;
    for(current = start; current; current = current->next) {
        if(current->pages == x) {
            current = current->next;
            break;
        }
    }
}

出于某种原因,这不起作用。我做错了什么?

3 个答案:

答案 0 :(得分:1)

您要离开列表,您需要if(current->pages == x)然后previous->next = current->next;并使用free(current)

void delete(int x) {
struct Book *current;
for(current = start; current; current = current->next) {
  if(current->next != NULL){
    if(current->next->pages == x) {
        current->next = current->next->next;
        break;
     }   
   }
else if(current->pages == x){
 free(current);
 current = NULL;
}

}

}

答案 1 :(得分:1)

您需要从列表中删除节点。此外,最好将逻辑拆分为从列表结构中删除列表节点的方法,并将其拆分为实际删除列表节点的方法。

struct Book* unlink(int x, struct Book *root) {
    struct Book *current = root, *prev = root, *next = NULL;
    while (current) {
        if(current->pages == x) {
            next = current->next;
            if (prev != NULL) {
                prev->next = next;
            }
            return current;
        }
        prev = current;
        current = current->next;
    }
    return NULL;
}

int delete(int x, struct Book* root) {
    struct Book *found = unlink(x, root);
    if (found != NULL) {
        free(found->title);
        free(found->actor);
        free(found);
        return 0;
    }
    return -1;
}

答案 2 :(得分:1)

首先要了解从链接列表中删除节点背后的逻辑。 假设您有一个链接列表为x1-> x2-> x3-> x4,并且您想要从中删除x3。所以要删除x3,你所要做的就是让x2的next指针指向x4。但在你这样做之前,你应该释放分配给节点x3的内存。

这是一个实现这个的简单代码:

void delete(int x) {
struct Book *current;
for(current = start; current; current = current->next) {
if(current->next != NULL){
if(current->next->pages == x) {
    Struct Book * temp = current->next; //save the address of the node to be deleted
    current->next = current->next->next; //remove the node from the linked list
    free(temp->author);
    free(...); //whatever memory you want to release
    free(temp);   //free the memory
    break;
   }   
 }
}
}

上述实现不包括当要删除的节点是列表的头节点或根节点时的情况。

void delete(int x) {
if(start == NULL)
    return; 
struct Book *current;
if(start->pages == x)
{
    Struct Book * temp = start; //save the address of the node to be deleted
    start = start->next; //remove the node from the linked list
    free(temp->author);
    free(...); //whatever memory you want to release
    free(temp); 
    return;
}
for(current = start; current; current = current->next)
{
if(current->next != NULL){
if(current->next->pages == x) {
Struct Book * temp = current->next; //save the address of the node to be deleted
current->next = current->next->next; //remove the node from the linked list
free(temp->author);
free(...); //whatever memory you want to release
free(temp);   //free the memory
break;
}   
}

}    }