c++ - 如何合并两个双向链表(访问下一个链接)
问题描述
我正在尝试合并两个双向链表。我已经创建了一个以正确顺序插入新节点的函数。参数由我的教授设置,所以我无法更改。我能够将第一项添加到 List1 但无法再添加。
我在尝试继续遍历 List2 并向 List1 添加更多项目时遇到错误。我尝试过递归和 do while 循环。在尝试使用 do-while 循环时
struct nodeType{
int info;
nodeType *next;
nodeType *back;
};
class OrderedDoublyLinkedList{
public:
//Insert x in appropriate place in the list to keep it
sorted
void insertNode(int x);
void mergeLists(OrderedDoublyLinkedList &List1,
OrderedDoublyLinkedList &List2);
private:
int count;
nodeType *first;
nodeType *last;
};
void
OrderedDoublyLinkedList::mergeLists(OrderedDoublyLinkedList
&List1, OrderedDoublyLinkedList &List2){
//First Technique
do{
List1.insertNode(List2.first->info);
List2.first->next; //Error: Expresion result unused
}
while(List2.first!=NULL)
//Second Technique
while(List2.first!=NULL)
List1.insertNode(List2.first->info);
mergeLists(&List1, &List2.first->next);
//If I try to use this it says cannot bind to a temporary of
type
我需要帮助访问下一个节点以将其余信息添加到 List1。
解决方案
看起来你只需要一个简单的 while 循环
nodeType* n = List2.first;
while (n != NULL)
{
List1.insertNode(n->info);
n = n->next;
}
虽然我仍然担心这是否是一个可以接受的解决方案。你说你需要搬进 List2
,List1
这不是这段代码的作用,这段代码复制 List2
到List1
,List2
不受这段代码的影响。
推荐阅读
- jquery - 基础 XML(使用 Jquery 提取)
- python - raise ValueError("Input contains NaN") ValueError: Input contains NaN 在尝试构建机器学习模型时
- flutter - 从 Flutter 中打开 Google 地图并选择地点
- connection - MULE-4:记录 SFTP 登录尝试
- angular - 配置 Angular 9 e2e cobertura 覆盖率报告的正确方法是什么?
- docker - `': 启动 docker 容器时没有这样的文件或目录 'sh`
- methods - Julia:为自定义类型定义方法
- r - 试图为我定义的函数运行一系列数字。但它只返回一个样本而不是 500
- reactjs - 为什么我的文档标题属性没有更新?
- linux - 将时间戳转换为日期会导致时间超出范围错误