gpt4 book ai didi

c - 根据匹配数据删除节点

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

说明:实现以下函数以按姓氏搜索,然后从链接列表中删除第一个匹配的学生。如果找到匹配的学生,该函数将返回一个指向新链表头部的指针;如果没有找到匹配的学生,则列表不变并返回链表的头。

当编译并运行这段代码时,每次只删除头节点。即使名称位于列表中间或根本不在列表中,头节点也始终会被删除。不太确定出了什么问题。任何帮助将不胜感激!谢谢!

STUDENT *DeleteByLastName(STUDENT *students, char *name)
{
struct STUDENT* current = students;
struct STUDENT* previous = NULL;

while (current != NULL) {
if (current->Lastname == name) {
if (previous == NULL) {
current = current->Next;
free(students);
students = current;
}
else {
previous->Next = current->Next;
free(current);
current = previous->Next;
}
}
else {
previous = current;
current = current->Next;
}
return current;
}
return NULL;

}

最佳答案

感谢您的提示!这是我为感兴趣的人提供的代码。

STUDENT *DeleteByLastName(STUDENT *students, char *name)
{
struct STUDENT* current;
struct STUDENT* head = students;

current = students;
int count = 0;
struct STUDENT* previous = NULL;

while (current != NULL) {
//check for matching head and delete
if (strcmp(current->Lastname,name) == 0 && count == 0) {
students = current->Next;
return students;
}
//If name matches but is not at the beggining of the list
if(strcmp(current->Lastname,name) == 0) {
previous->Next = previous->Next->Next;
current = current->Next;
return students;
}
else {
previous = current;
current = current->Next;
++count;
}
}
return head;
}

关于c - 根据匹配数据删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39132407/

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