如何在C中的双向链表中搜索名称和删除节点?
How to search name and delete node in doubly linked list in C?
我想在我的双向链表中搜索名称并删除,但最后出现Segmentation fault (core dumped)错误。
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;
}
}
}
我想在我的双向链表中搜索名称并删除,但最后出现Segmentation fault (core dumped)错误。
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;
}
}
}