c - 删除链表中的内容?

标签 c linked-list

我编写了以下代码:

#include<stdio.h>

struct student{
char name[25];
double gpa;
struct student *next;
};

struct student *list_head;

struct student *create_new_student(char nm[], double gpa) 
{
         struct student *st;
         printf("\tcreating node\t");
         printf("\nName=%s \t Gpa= %.2f\n", nm, gpa);

         st = (struct student*)malloc(sizeof (struct student ));
         strcpy(st->name, nm);
         st->gpa = gpa;
         st->next = NULL;
         return st;
}

void printstudent(struct student *st) 
{
         printf("\nName %s,GPA %f\n", st->name, st->gpa);
}

void insert_first_list(struct student *new_node) 
{
         printf("\nInserting node: ");
         printstudent(new_node);
         new_node->next = list_head;
         list_head = new_node;
}

struct student *delete_first_node() 
{
         struct student *deleted_node;
         printf("\nDeleting node: ");
         printstudent(deleted_node);
         list_head = list_head->next;
         return deleted_node;
}

void printlist(struct student *st)
{
         printf("\nPrinting list: ");
         while(st != NULL) {
             printstudent(st);
             st = st->next;
         }
}

int main() 
{
         struct student *other;
         list_head = create_new_student("Adil", 3.1);
         other = create_new_student("Fatima", 3.8);
         insert_first_list(other);
         printlist(list_head);
         other = delete_first_node();
         printlist(list_head);
         return 0;
}

当我运行它时,没有错误或警告。但是,它停在删除部分。该消息表明程序已停止工作。

你能帮我找出问题所在吗?

最佳答案

在函数 delete_first_node 中,节点 deleted_node 未初始化并传递给尝试访问其成员的函数 printstudent,导致 未定义的行为
该函数应该是

struct student *delete_first_node(){
    struct student *deleted_node = list_head;
    printf("\nDeleting node: ");
    if(deleted_node != NULL)
    {
        printstudent(deleted_node);
        list_head= list_head->next;
        free(deleted_node);
    }
    else
       printf("List is emty\n");

    return list_head;
}

关于c - 删除链表中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24342265/

相关文章:

java - 从java中的链表保存数据?

c - 释放链表中的前一个节点

c - C 中结构解引用运算符的更复杂表示法是 ->?

c - 全局数组问题不更新,C 编程

c - 如果可能的话,如何在 C 中定义 2 位数?

c - C语言中如何从数组中随机选取元素?

c - 将 char* 添加到链表不起作用

c - 将参数传递给 pthread 会导致重复 C

c - 链接列表 - 切换元素

java - 在特定点后添加节点链表Java