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

标签 c list intersection

所以目标是返回一个新的链表,它是两个列表 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/

相关文章:

c++ - 钩。 va_list 。可能吗?

c# - 将元素均匀地添加到列表中

intersection - 如何从 OpenStreetMap 中找到交叉点?

python - 计算两个列表的所有幂集交集

c - Valgrind 的输出缺少基本值

c - C99 inline 背后的想法是什么?

python - 根据分隔符后的字符分割字符串 - python

python - 从python中的列表中提取数组

ios - Objective-C 检查旋转的 UIView 的 subview 是否相交?

带有定义的 C 宏构建