C 在链接列表中删除?
我编写了以下代码:C 在链接列表中删除?,c,linked-list,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
#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;
}
#包括
结构学生{
字符名[25];
双gpa;
结构学生*下一步;
};
结构学生*列表头;
结构学生*创建新学生(字符nm[],双gpa)
{
结构学生*st;
printf(“\t创建节点\t”);
printf(“\nName=%s\t Gpa=%.2f\n”,nm,Gpa);
st=(结构学生*)malloc(结构学生人数);
strcpy(st->name,nm);
st->gpa=gpa;
st->next=NULL;
返回st;
}
无效打印学生(结构学生*st)
{
printf(“\n名称%s,GPA%f\n”,st->name,st->GPA);
}
void insert_first_list(结构学生*新节点)
{
printf(“\n插入节点:”);
printstudent(新的_节点);
新建节点->下一步=列表头;
列表头=新节点;
}
结构学生*删除第一个节点()
{
struct student*已删除\u节点;
printf(“\n删除节点:”);
printstudent(已删除的_节点);
列表头=列表头->下一步;
返回删除的_节点;
}
无效打印列表(结构学生*st)
{
printf(“\n打印列表:”);
while(st!=NULL){
印刷学生(st);
st=st->next;
}
}
int main()
{
结构学生*其他;
列表头=创建新学生(“Adil”,3.1);
其他=创建新学生(“Fatima”,3.8);
插入第一个列表(其他);
打印列表(列表标题);
其他=删除第一个节点();
打印列表(列表标题);
返回0;
}
当我运行它时,没有错误或警告。但是,它在删除部分停止。消息说程序已停止工作
您能帮我找到问题吗?在函数
首先删除\u节点中
节点已删除的\u节点
未初始化并传递给函数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;
}
该消息表示程序已崩溃。借助调试器解决问题。@user3096716;请看,您需要释放我忘记提到的已删除节点。查看新的编辑。