gpt4 book ai didi

c - 如何实现删除节点的功能?

转载 作者:行者123 更新时间:2023-11-30 18:59:31 27 4
gpt4 key购买 nike

我一直在创建一个对我来说正常工作的node_add函数,但我很难创建一个 node_delete 节点。

这是我写的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
typedef struct friend // The struct
{
char *name;
int age;
char gender;
struct friend* next; // A pointer that points to the next node in the linked list
}friend;
void node_delete(); // The deleting node function
friend* head; // Definging the head of the linked list
void node_delete() // Deleting a node
{
char name[256];
printf ("Please enter the friend's name you want to delete: \n");
fgets (name, 256, stdin);
fgets (name, 256, stdin); // Getting the name of the person that the user wants to delete
while (head -> next != NULL) // As long the node isnt the last one
{
if (0 == (strcmp(head -> name, name))) // If the name that the user entered matchs a name in the linked list,
{ // It'll skip it
head -> next = head -> next -> next; // Deletes a node from the linked list
}
head -> next; // Going to the next node
}
free(head); // Freeing the deleted node
}

我只有删除节点功能有问题

最佳答案

if (head) {
if (strcmp(head->name, name) == 0) {
to_free = head;
head = head->next;
free(to_free);
} else {
list = head;
while (list->next) {
if (strcmp(list->next->name, name) == 0) {
to_free = list->next;
list->next = list->next->next;
free(to_free);
break; // if only one
}
list = list->next;
}
}
}

关于c - 如何实现删除节点的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459332/

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