c - 从链表中递归删除数字

标签 c recursion data-structures struct linked-list

大家好我做了一个函数,它根据你想从链表中删除的数字递归地从链表中删除。但是在删除之后,如果我试图打印列表的堆栈,并且出现运行时错误,因为在删除之后,数字的位置什么也没有。我怎样才能完成代码?

 struct node* delete_item(struct node* head, int num)
{
    if (head == NULL) { // Found the tail
        printf("not found\n");
        return NULL;
    }
    else if (head->data == num) 
    { // Found one to delete
        head = head->next;
        free(head);
        printf("num founded");
        return head->next;
    }
    else 
    { // Just keep going
        head->next = delete_item(head->next, num);
        return head;
    }
}

最佳答案

您释放了应返回的内容并解除了指向已释放内容的指针的引用。这是错误的。

你应该引入一个缓冲区来存储应该返回的内容。

struct node* delete_item(struct node* head, int num)
{
    if (head == NULL) { // Found the tail
        printf("not found\n");
        return NULL;
    }
    else if (head->data == num) 
    { // Found one to delete
        struct node* next = head->next;
        free(head);
        printf("num founded");
        return next;
    }
    else 
    { // Just keep going
        head->next = delete_item(head->next, num);
        return head;
    }
}

关于c - 从链表中递归删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574396/

相关文章:

c - 程序不接受文件中的所有值

java - 难以理解递归

javascript - 如何在没有 for 循环的情况下在控制台中显示数字?

java - 二叉树节点 - 哪条路?

C: 存储命令历史的数据库

c - Shmap 3.2 恢复共享内存的指针

c - 链接列表更改

c - 过程识别

c - 矩阵内对角线交点的元素北、南、东、西

objective-c - 递归不崩溃