我想写一些函数,在这些函数中,你可以在列表中插入一个学生(名字,id)并删除他。如果学生已经在列表中,我删除了他,然后试图再次插入他,程序输出。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;
}
我基本上是想插入->删除->插入同一个节点。
我只是修改了list_push_back函数,它的工作,目前XD。
//enters the new student in the end of the list
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;
student tmp = l->head;
if (list_isempty(l))
{
l->head = new_student;
}
else
{
while (tmp->next!=NULL)
{
tmp = tmp->next;
}
tmp->next = new_student;
}
l->tail = new_student;
l->size++;
return l;
}