c - 递归两个列表之间的差异
问题描述
我正在尝试做的练习要求我,给定两个列表(L1 和 L2),其中没有重复项,创建第三个列表,其中包含仅存在于 L1 中的元素。
我想到的解决问题的第一种方法是获取列表 L1 的每个节点并将其与整个列表 L2 进行比较,如果该节点不存在,那么我将其添加到我必须构建的新列表中。我的问题是我不明白如何处理这一步。
我已经了解了练习的基本案例。如果 L1 为空,则返回 NULL(例如)。如果 L1 不为空,但 L2 为空,那么我只需返回 L1。
例子:
L1:15->13->2->3->70->100
l2:3->13->5->27->100->101
输出:
L3:15->2->70
这是我的尝试:
//struct
struct data
{
int d;
struct data d;
};
typedef struct data Node;
//create the list
Node *creat_list() {
Node *lis, *p, *last;
int x;
printf("\n Insert new data: ");
scanf("%d", &x);
if(x <= 0)
{
lis = NULL;
}
else
{
last = newnode();
lis = last;
last->d = x;
last->next = NULL;
printf(" Insert new data: ");
scanf("%d", &x);
while(x > 0)
{
p = newnode();
p->d = x;
p->next = NULL;
last->next = p;
last = p;
printf(" Insert new data: ");
scanf("%d", &x);
}
}
return (lis);
}
Node *list_difference(Node *l1, Node *l2) {
Node *l3;
if (l1 == NULL) return NULL;
if (l1 != NULL && l2 == NULL) return l1;
if (l1 != NULL && l2 != NULL)
{
...
...
}
return l3;
}
解决方案
推荐阅读
- c++ - 如何将 SSAO 应用于天空盒?
- javascript - 如何在 Angular Firebase 中修复浏览器刷新时的“TypeError:无法读取属性 'getIdToken' of null”?
- sql - 稍微修改SQL给我带来:ORA-01427:单行子查询返回多于一行
- python - concurrent.futures ThreadPoolExecutor - 线程数不匹配
- selenium - Selenium IDE 3.x - 验证变量的内容
- javascript - HTML5 音频播放器未在 ios Safari 中自动播放
- go - 如何区分哪些依赖项是可下载的?
- assembly - 我的汇编代码为字符串长度计算了一个额外的字节
- facebook - 使用 Facebook API 获取全球观看次数最多的视频
- python - 在python中实现特定的分布