gpt4 book ai didi

c - 使用 C 实现 2 个链表的交集

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

所以目标是返回一个新的链表,它是两个列表 a 和 b 的交集,即两个列表共有的所有项目的列表。交叉点中的项目是唯一的。

我的代码导致段错误,问题是什么?

SLList *
sllist_intersection(SLList *a, SLList *b) {
SLEntry * e = b->head;
SLList * list;
list->head = NULL;
SLEntry * f = a->head;
while (e != NULL) {
while (f != NULL) {
if (e->value == f->value) {
sllist_add_end(list, e->value);
break;
}
f = f->next;
}
e = e->next;
f = a->head;
}
return list;

这是我忘记包含的头文件:

  2 struct SLEntry {
3 int value;
4 struct SLEntry * next;
5 };
6
7 typedef struct SLEntry SLEntry;
8
9 struct SLList {
10 SLEntry * head;
11 };
12
13 typedef struct SLList SLList;
14
15 void sllist_init(SLList * list);
16 void sllist_add_end( SLList *list, int value );
17 int sllist_remove(SLList *list, int value);
18 void sllist_remove_interval(SLList *list, int min, int max);
19 SLList * sllist_intersection(SLList *a, SLList *b);
20 void sllist_print(SLList *list);

最佳答案

您的代码的问题是内存分配。

1.在执行list->head=NULL之前,为list分配一些内存。您可以在此处使用malloc。

SLList * list=malloc(sizeof(SLList));

没有为指针分配内存,因此无法初始化其成员。

关于c - 使用 C 实现 2 个链表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29354725/

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