【发布时间】:2020-09-09 05:46:34
【问题描述】:
我正在尝试编写一些函数,您可以在其中插入一个学生(姓名,身份证)到列表中并删除他。如果学生已经在列表中,我删除了他,然后尝试再次插入他,程序输出:Student added successfuly 但他没有出现在列表中。当我再次运行程序并尝试插入他(这次他不存在于列表中)时,程序运行正常。请注意,所有内容均基于学生的 id 而不是他的姓名。以下是函数:
int addStudent(student st, list l){
if (findStudent(st->id, l) == NULL)
{
list_push_back(l, st->name, st->id);
return 1;
}
return 0;
}
student findStudent(int id, list l){
student stTemp = l->head;
if (l->size != 0)
{
while (stTemp != NULL)
{
if (stTemp->id == id)//check if the student's id is the same as the student's id in the struct
{
return stTemp;
}
stTemp = stTemp->next;
}
}
return NULL;
}
list list_push_back(list l, char *name, int id)
{
student new_student = malloc(sizeof(struct studentR));
if (new_student == NULL)
{
printf("Error allocating memory\n");
abort();
}
strcpy(new_student->name, name);
new_student->id = id;
new_student->next = NULL;
if (list_isempty(l))
{
l->head = new_student;
}
else
{
l->tail->next = new_student;
}
l->tail = new_student;
l->size++;
return l;
}
int deleteStudent(student st, list l){
//check if the list is empty
if (list_isempty(l))
{
return 0;
}
//check if the student is in the list
st = findStudent(st->id, l);
if (st == NULL)
{
return 0;
}
student temp = l->head;
student prev = temp;
//if student to be deleted is the first in the list
if (l->head->id == st->id)
{
l->head = temp->next;
free(temp);
l->size--;
return 1;
}
//if student to be deleted is the last in the list
if (l->tail == st->next)
{
while (temp->id != st->id)
{
prev = temp;
temp = temp->next;
}
prev->next = NULL;
l->tail = prev;
free(temp);
l->size--;
return 1;
}
while (temp->id != st->id)
{
prev = temp;
temp = temp->next;
}
prev->next = temp->next;
free(temp);
l->size--;
return 1;
}
我基本上是在尝试插入->删除->插入同一个节点
【问题讨论】:
-
你应该尽可能地孤立地开发新功能;为仅包含 int 的 Student 编写一个链表,并在尝试添加字符串之前使其完美运行。
-
你是对的。我什至没有想到这一点。但是我快到最后期限了,你能帮我解决这个问题吗?不想要也没关系
-
我会尝试一下,但是 1) 你还没有发布 minimal complete example,这让事情变得很困难,并且 2) 你似乎忽略了很多编译器错误和警告.
-
我解决了。我刚刚更改了 list_push_back 函数中的一些代码,现在它似乎工作正常。我也没有收到任何警告或错误。
标签: c struct file-io linked-list