c - 删除链表头后出现垃圾打印

标签 c linked-list

每个教室学生(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/

相关文章:

java - 数字格式异常和正则查询

python - 双链表中间插入不起作用

c - 使用链接列表时 While 循环失败

C 标记化并存储到数组中

c - 在 OpenCV 的不同窗口中显示多个图像

c - 如何在 C 中声明指向结构数组的指针

c - 链接列表不起作用

C++ 创建有序链表

c - 为什么编译器认为我在 "pow"中使用 double, 。 'double' 到 'float' C4244

c - select(2)为什么叫 "synchronous"多路复用?