gpt4 book ai didi

c - C语言中如何在双向链表中查找名称并删除节点?

转载 作者:行者123 更新时间:2023-11-30 16:14:09 25 4
gpt4 key购买 nike

我想在双向链表中搜索该名称并删除,但最后出现了段错误(核心转储)错误。

typedef struct NODE {
char *name;
struct NODE *next;
struct NODE *prev;
} node_t;

void delnode(struct NODE** head, char* search_name) {
struct NODE* search_node =
(node_t*)malloc(sizeof(node_t));
struct NODE* current = *head;
search_node->name = search_name;
while(current->name!=search_name)
current = current->next;
current->prev->next = current->next;
current->next->prev = current->prev;
current->prev = NULL;
current->next = NULL;
}

最佳答案

并且不要忘记更新*head的值。我将尝试将所有评论总结如下:

void delnode(struct NODE** head, char* search_name) {
struct NODE* current;
for(current=*head; current; current = current->next) {
if (!strcmp(current->name, search_name)) {
if (current->next)
current->next->prev = current->prev;
if (current->prev)
current->prev->next = current->next;
if (current == *head)
*head = current->next;
current->prev = NULL;
current->next = NULL;
free(current);
return;
}
}
}

关于c - C语言中如何在双向链表中查找名称并删除节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57835114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com