c - 仅删除一次具有特定值的链表

标签 c linked-list

我正在编写一个程序,在其中一个函数中,我必须从 LinkedList 中删除一个值

struct node *delete_val(int value, struct node *head) {

struct node *h1 = head;
if (head == NULL) { return NULL;}
if (head->next == NULL) { free(head); return NULL;}
while (h1 != NULL) {
    if (h1->next != NULL && h1->next->data == value){
        h1->next = h1->next->next;
        } else {
    h1 = h1->next;
}
free(h1);
return head;
}
}    

如果通过:

(4,[3,4,5,6,4,4,7]);

函数应该返回:

[3,5,6,4,4,7]

但是我的函数出现了错误:

Error: the list returned by your function is invalid. The next field of node 0 is invalid (0xf5400650).

我基本上是在检查下一个节点是否在其“数据”(head->next->data) 中包含匹配值,如果是,我将重新切换当前链表的指针(head->next) 到它之后的那个 (head->next->next) 但我什至无法让它工作。

最佳答案

有两个问题。

  1. 您需要在更正链接后中断(因为您要删除一次值)
  2. 您正在释放错误的成员。

如果你把这两个都改正了,我觉得应该就可以了。

struct node *delete_val(int value, struct node *head) {
    struct node *h1 = head;
    struct node *tmp =  NULL;

    if (head == NULL) { return NULL;}
    if (head->next == NULL) { free(head); return NULL;}

    while (h1 != NULL) {
        if (h1->next != NULL && h1->next->data == value){
            tmp = h1->next;
            h1->next = h1->next->next;
            break;            
        } else {
            h1 = h1->next;
        }    
    }

    free(tmp);
    return head;
}

关于c - 仅删除一次具有特定值的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549095/

相关文章:

c - 我怎么知道数组中的元素是否存在?

c - 动态内存分配和内存泄漏

c - 执行 Lex 和 Yacc 的顺序?

algorithm - 如何在不修改指针的情况下递归地反转单链表?

c - 矩阵作为函数参数

c - 我们需要在 wordexp 失败时调用 wordfree 吗?

C - 链表 - 删除头部 - 段错误

c++ - 如何在嵌套类中重载 << 运算符

c - 访问链表中的结构

c++ - 列表中倒数第二个元素的迭代器