首页 > 解决方案 > 递归两个列表之间的差异

问题描述

我正在尝试做的练习要求我,给定两个列表(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;
}

标签: clistlinked-list

解决方案


推荐阅读