将 2 个链表中包含的相同值写入另一个链表
Write the same values that contained in 2 linked list into another linked list
我想编写创建新的单向链表的函数,并将包含在另外两个单向链表中的相同值写入其中。我用嵌套的"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,l2,new_list,next(初始化为某些东西。在C++(11 及更高版本(中,将它们初始化为 nullptr,在较旧的 C++ 和 C 中,将它们初始化为 NULL。如果你不这样做,它们有一个随机值,你的代码正在读取和写入它不拥有的内存。
注意:我假设 add(( 会在您向它传递空指针时分配一个新的列表结构。
list* l = NULL;//只需在main中将其初始化为NULL。
list* l2 = NULL;//只需在main中将其初始化为NULL。
/* 现在您的代码将正常工作。
相关文章:
- 将库链接到另一个应用程序时,CMAKE 找不到库
- 将一个 QWidget 链接到另一个新创建的 QWidget
- 如何将数据从一个结构链接到另一个结构
- C++链表最后一个元素的迭代器?
- 是否可以将 EXE 文件作为 lib 文件链接到另一个项目?
- 无法在 CMake 中创建动态库并将其链接到另一个动态库?
- 如何将一个 exe 项目链接到另一个 exe 项目中的类
- 链接另一个文件中的函数时,Qt 上出现错误 LNK 2019
- QMAKE:将静态库链接到另一个静态库
- CMAKE:将静态库从子目录链接到另一个子目录中的可执行文件
- 如何根据目标体系结构将共享库链接到另一个共享库
- 链表:最后一个指针不是NULL
- 如何将包含其他第三方C库的C++项目a链接到另一个项目B
- 链接另一个静态库中的静态库
- 我可以创建一个链接另一个库但不依赖于其include的c++库吗
- 链接到链接到另一个共享库的共享库会在退出时出错
- 将共享库链接到另一个共享库
- GCC - 链接到另一个文件夹中的库有效,但二进制文件不会运行
- 如何在C++中将一个.exe链接到另一个.exe
- 删除单向链表最后一个元素的递归方法