无法从单向链表中删除

标签 c linked-list singly-linked-list

所以我有这个结构:

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;
        }
    }
}

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

最佳答案

首先了解从链表中删除节点的逻辑。 假设你有一个链接列表 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;
}   
}

}

关于无法从单向链表中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38201592/

相关文章:

c - 为什么我们不必释放 C 中结构的嵌入式指针

c - C语言中的简单链表程序

c++ - 在 C++ 中实现链表,我哪里出错了?

c - 按升序将值插入已排序的链表

c - 为什么以下在单链表末尾插入节点的代码不起作用?

c - 我有一个链接列表,我想删除重复的值

c++ - 如何不在项目文件之一中添加预编译头

c - 使用 scanf 定义 malloc 数组大小并初始化

实际应用中等待所有 child 的正确方法

java - 将链表的所有其他元素(就地)移动到java中链表的末尾