gpt4 book ai didi

c - 从链表开头删除

转载 作者:行者123 更新时间:2023-11-30 16:59:09 25 4
gpt4 key购买 nike

这是我的代码,用于从包含学生记录的链接列表的开头删除。

    int delete (struct student **q) {
struct student *current;
current=(struct student *)malloc(sizeof(struct student));
current=head;
head=current->link;
free(current);
//display(current);
return 1;
}

这是结构

struct student
{
int id;
char name[10];
char gender[10];
struct student * link;
}*head;

但不是删除整个记录只是id改为0

before deletion
ID Name Gender
1 Yazhini Female
2 Anu Female
3 Janavi Female
4 Haritha Female

删除后

  ID       Name Gender
0 Yazhini Female
2 Anu Female
3 Janavi Female
4 Haritha Female

最佳答案

该函数可以如下所示

int delete( struct student **head ) 
{
int success = *head != NULL;

if ( success )
{
struct student *current = *head;
*head = current->link;
free( current );
}

return success;
}

对于你的函数来说,它至少有一个内存泄漏,因为首先分配了一个节点的内存,并将其地址分配给了变量 current

current=(struct student *)malloc(sizeof(struct student));

然后这个变量被重新赋值。

current=head;

也不清楚参数 q 的含义。

关于c - 从链表开头删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38330415/

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