gpt4 book ai didi

c - 删除链表中的内容?

转载 作者:行者123 更新时间:2023-11-30 15:32:13 25 4
gpt4 key购买 nike

我编写了以下代码:

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com