每个教室学生(aluno
)代表一个链表节点。
按学生姓名删除后,我的打印功能会在删除的学生之前的“位置”上打印垃圾。
[编辑]添加了完整代码。
完整代码:
#include <stdio.h>
#include <stdlib.h>
struct student{
char *name;
int number;
struct student *next;
};
struct student *constructor(char *name, int number){
struct student *newNode = (struct student *)malloc(sizeof(struct student));
newNode->name = name;
newNode->number = number;
newNode->next = NULL;
return newNode;
}
struct student *newStudent(struct student *node, char *name, int number){
if (node == NULL)
constructor(name, number);
struct student *p = node;
while(p->next != NULL) p = p->next;
p->next = constructor(name,number);
return node;
}
struct student *removeAluno(struct student *node, char *name){
struct student *p = node;
if (strcmp(p->name,name) == 0){
struct student *devolver = p->next;
free(p);
return devolver;
} //Removes head
while(p->next != NULL){
if (strcmp(p->next->name,name) == 0){
if (p->next->next == NULL){ //Removes last element
struct student *remover = p->next;
p->next = NULL;
free(remover);
}
else{ //Removes any element between head and last
struct student *remover = p->next;
p->next = p->next->next;
free(remover);
}
}
else
p = p->next;
}
return p;
}
void printClass(struct student *students){
struct student *p = students;
while(p->next != NULL){
printf("\nNome: %s, Numero: %d",p->name,p->number);
p = p->next;
}
printf("\nNome: %s, Numero: %d",p->name,p->number);
printf("\n");
}
int main(){
struct student *a = constructor("Michael",15);
newStudent(a,"John",14);
newStudent(a,"Jack",13);
printClass(a);
removeAluno(a,"Michael");
printClass(a);
removeAluno(a,"John");
printClass(a);
removeAluno(a,"Jack");
printClass(a);
return 0;
}
我的输出:
//list after inserting Michael, John, Jack (in this order)
Nome: Michael, Numero: 15
Nome: John, Numero: 14
Nome: Jack, Numero: 13
//list after removing Michael
o, Numero: 7283408 //junk
Nome: John, Numero: 14
Nome: Jack, Numero: 13
//list after removing John
o, Numero: 7283408 //junk
Nome: Jack, Numero: 13
//list after removing Jack
Nome: ╚6o, Numero: 7283408 //junk
最佳答案
您的函数返回
结构指针,但在main
中您不使用它们的返回。您需要做的是 main
-
a=newStudent(a,"John",14);
其他功能也一样。
关于c - 删除链表头后出现垃圾打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38019489/