gpt4 book ai didi

c - 从链接列表中删除单个学生

转载 作者:行者123 更新时间:2023-11-30 15:05:44 26 4
gpt4 key购买 nike

我无法让这个功能正常工作。当我尝试删除特定记录时它崩溃了。我需要更改什么才能使其按预期工作?

//Delete Students Function
void delete_single_Student(Student *pfirst, int id)
{
int search_id;
bool found = false;

Student *pcurrent = pfirst;
Student *temp = NULL;


printf("Please enter the student ID of the student that will be deleted.\n");
scanf("%d", &search_id);

while (search_id < 999 || search_id > 9999)
{
printf("\nPlease enter a valid id.\n");
scanf("%d", &search_id);
}
do
{
temp = pcurrent;
pcurrent = pcurrent->next;

if (pfirst->id == search_id)
{
found == true;
printf("**********************\n\n");
printf(" Student %d Deleted \n\n", search_id);
printf("*********************\n\n");
pfirst = pfirst->next;
free(temp);
break;
}

} while (found != true);
}

最佳答案

请注意,您正在查询 pfirst,但通常不会在循环中更改 pfirst。仅当第一个元素是您的结果时,条件才为真。此外,found != true 始终为 true,因此在遍历列表并引用 pcurrrent->next 后,您必然会得到一个 pcurrent 空指针。

我建议您逐步解决更简单的问题。

1) 只需编写一个过程来打印每个元素,当指针为空时终止。您不需要找到的变量。

2) 重复数字#1,但将该元素与其前一个元素并排打印,要求您跟踪前一个元素。

3)掌握#2之后,您将发现第一个元素是一个特殊情况,如果不访问调用函数所拥有的信息,您就无法真正解决问题。

关于c - 从链接列表中删除单个学生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39670971/

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