c++ - 如何组合或合并 2 个链接列表以创建新列表?
问题描述
我正在尝试获取两个链表“list_1”和“list_2”,然后将它们组合起来放入“list_3”。我创建了两个列表,但似乎无法弄清楚如何组合它们。我添加的代码是我创建列表的方式。非常新的指针和链表,所以任何帮助将不胜感激,谢谢!
struct node
{
int data;
node *next;
};
class List
{
public:
node *head, *tail;
List()
{
head = NULL;
tail = NULL;
}
void add_node(int n)
{
for(int i = 1; i <= 1; i++)
{
node *temp = new node;
temp -> data = n;
temp -> next = NULL;
if(head == NULL)
{
head = temp;
tail = temp;
}
else{
tail -> next = temp;
tail = tail -> next;
}
}
}
解决方案
您必须“重新布线”它们。head
列表 B 的对象应该重新连接到tail
列表 A 的对象,这样您就可以删除List
列表 B 的对象,但不会删除其成员。引入新的方法merge(List* list)
参数,并重新连接this->tail
到list->head
,并更新this->tail
为list->tail
。
推荐阅读
- pool - Toloka 任务页面是如何创建的
- react-native - 'C:\Users\jansen' 不是内部或外部命令、可运行程序或批处理文件
- android - 如何将特定的 youtube 播放列表加载到 android 电视应用程序中
- flutter - Flutter:Listview 在 iOS 上滚动,但在 Android 上不滚动
- php - 更轻松?一次搜索 str_replace。一个命令更多找到?
- python - 如何使用 seaborn 制作以下条形图?
- python - OLS 回归:预测到某个总数
- netcdf - 通过 ncview 在 netcdf 文件中显示错误的初始化值
- c# - Post 方法在发送内存大小大于 30MiB 的对象时收到 null
- html - 行之间的垂直黑线 HTML!怎么修?