各クラスの学生(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
ポルトガル語と英語の混在?英語の変数、関数、型名のみを使用するように質問をリファクタリングしてください。 – Jezor
印刷機能では、未定義の動作を引き起こす 'NULL'へのポインタを逆参照しようとするので、最後の' printf'を削除してください。 – ameyCU
@ameyCUその時点で「NULL」ではないと思います... –