将 2 个链表中包含的相同值写入另一个链表

Write the same values that contained in 2 linked list into another linked list

本文关键字:链表 另一个 包含      更新时间:2023-10-16

我想编写创建新的单向链表的函数,并将包含在另外两个单向链表中的相同值写入其中。我用嵌套的"for"循环写下了解决方案,我不明白为什么它不起作用。

struct list {
    int data;
    list *next;
};
// Adding
list* add(list* l, int x)
{
    if (l == NULL)
    {
        l = new list;
        l->data = x;
        l->next = NULL;
        return l;
    }
    list* temp = l;
    while (temp->next != NULL)
    {
        temp = temp->next;
    }
    list* p = new list;
    p->data = x;
    p->next = NULL;
    temp->next = p;
    return l;
}
// That function generates SegFault 11
list* foo(list* l1, list* l2) {
    list* new_list;
    for (list* temp1 = l1 ; temp1 != NULL; temp1 = temp1->next) {
        for (list* temp2 = l2; temp2 != NULL; temp2 = temp2->next) {
            if (temp1->data == temp2->data) {
                new_list = add(new_list, temp1->data);
            }
        }
    }
    return new_list;
}
// show() code
int main(int argc, char const *argv[]) {
    list* l;
    l = add(l, 13);
    l = add(l, 34);
    l = add(l, 13);
    l = add(l, 7);
    l = add(l, 90);
    show(l);
    cout << endl;
    list* l2;
    l2 = add(l2, 13);
    l2 = add(l2, 61);
    l2 = add(l2, 48);
    l2 = add(l2, 7);
    l2 = add(l2, 90);
    cout << endl;
    show(l2);
    cout <<  endl;
    list* l3 = foo(l, l2); // 13 7 90
    show(l3);
    return 0;
}

我期待'13 7 90'。但收到分段错误。为什么?我用add((函数

list* l = NULL;//只需在main中将其初始化为NULL。

list* l2 = NULL;//只需在main中将其初始化为NULL。

/* 现在您的代码将正常工作。