如何通过运算符重载连接两个单独链接的列表
How to concatenate two singly linked lists via operator overloading?
这是我的头文件
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <string>
using namespace std;
class Node
{
friend class LinkedList;
public:
Node(string& name, int num) :studentName(name), RUID(num)
{
this->next = NULL;
}
private:
string studentName;
int RUID;
Node *next;
};
class LinkedList
{
public:
LinkedList();
~LinkedList();
LinkedList& operator+(LinkedList &i);
//LinkedList operator=();
void makeLists(int n);
void addNode(LinkedList &i);
void removeNode();
void printList();
void printElement();
void sortList();
private:
Node *head;
Node *tail;
int size;
};
#endif
这是我的操作员+功能
LinkedList& LinkedList::operator+(LinkedList &i)
{
LinkedList tohma;
tohma = *this;
tohma += i;
return tohma;
}
我收到一条+=运算符的错误消息,但我不知道该如何以不同的方式执行。我觉得我很接近,但也许我犯了一个逻辑错误?
任何和所有的帮助都将不胜感激
通常,LinkedList
的operator+
的结构如下:
LinkedList operator+(const LinkedList& _list) {
// ptr to list to return, initialised with this
LinkedList* ret_list = this;
// temporary node ptr for iterating through _list
Node* temp = _list.head;
// loop through contents of _list
while (temp != nullptr) {
// insert data from _list to ret_list
ret_list->insert(temp->data);
// ^= this will need to be changed for your specific list fields and insert methods
temp = temp->next;
}
return &ret_list;
}
至于operator+=
,它有类似的逻辑:
LinkedList& operator+=(const LinkedList& _list) {
Node* temp = _list.head;
while (temp != nullptr) {
insert(temp->data);
temp = temp->next;
}
return *this;
}
我这里可能有点不对劲,因为已经很晚了,但应该是准确的。
LinkedList LinkedList::operator+(const LinkedList &i)
{
LinkedList* tohma = this;
Node* temp = i.head;
tohma->tail->next = temp;
return *tohma;
}
由于我已经为第一个列表保存了拖尾节点,所以我可以使用它将其与第二个列表
连接起来相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 两个单独的类不共享相同的数据 C++
- SDL GPU 为什么将两个图像分成两个单独的循环更快?
- 如何将4位整数值转换为C 中两个单独的2位值
- 在OpenGL中制作两个单独的茶壶
- 将INT和STR输入并将它们存储到两个单独的列表中
- 如何将一个类的两个单独实例设置为彼此相等的 c++
- GCC 6.3.0 中的 ODR 冲突,类型在两个单独的翻译单元中定义
- 尝试使用两个单独的 getline() 实例来填充两个单独的向量
- C++:两个单独的函数在嵌套时返回不同的结果?
- 模板和两个单独的类之间的区别
- 如何避免将两个单独的'>'格式化为一个班次?
- 输入坐标分为与文件故障的两个单独的数组
- 如何使用两个单独的语法实现计算机翻译器
- 相当棘手的代码气味要解决(由于两个单独的库)C
- 如何组合两个单独的生成文件来编译程序
- 为什么 setprecision( ) 在一个数字中给我两个单独的小数点
- 在两个单独的应用程序之间共享 dll 中的堆内存