我正在尝试深入研究 C++ 中的数据结构。因此,我正在学习如何编写列表。在重载求和运算符 + 之前,一切似乎都运行良好。对于两个给定的列表,它将列表中两个最高值相加。
这是 .h 文件:
typedef struct rob{
int value;
struct rob* next;
}element;
class list{
public:
friend list& operator+(list&,list&);
friend void merge(list& x,list& y);
void show();
bool search(int x);
void append(int x);
bool sortAppend(int x);
list& operator--(int);
bool empty() { return (inf.head==nullptr);}
void clear() { inf.head = nullptr; }
list() { inf.head = inf.tail = nullptr; }
~list() { while(!empty()) { (*this)--;}}
private:
typedef struct{
element* head;
element* tail;
}info;
info inf;
};
我知道在 .h 文件中,typedef 可能看起来有点像 C,但标题设计是从我正在学习的书中复制的。我正在尝试通过作者的想法自己破解这些方法。
及相关函数定义:
#include "list.h"
bool list::sortAppend(int x){
element* newElem = new element;
newElem->value = x;
if (empty()){
inf.head=inf.tail=newElem;
newElem->next=nullptr;
return true;
}
else if ( (newElem->value) < (inf.head->value) ){
newElem->next=inf.head;
inf.head=newElem;
return true;
}
else if ( (newElem->value) > (inf.tail->value) ) {
newElem->next=nullptr;
inf.tail->next=newElem;
return true;
}
element* tempHead = inf.head;
while(tempHead!=inf.tail){
if ( (newElem->value) < (tempHead->next)->value) {
newElem->next = (tempHead->next);
tempHead->next = newElem;
return true;
}
else{
tempHead = tempHead->next;
}
}
return false;
}
list& operator+(list& X, list& Y){
list* tempListArr[2] = {&X, &Y};
list* tempList = new list;
for(const list* i: tempListArr)
{
element* tempHead = (i->inf).head;
while(tempHead!= nullptr){
tempList->sortAppend(tempHead->value);
tempHead = tempHead->next;
}
tempList->show();
std::cout << "--\n";
}
return *tempList;
}
对于包含值的给定列表:
#include <iostream>
#include "list.cpp"
int main(){
list myList;
myList.sortAppend(5);
myList.sortAppend(2);
myList.sortAppend(4);
list myList2;
myList2.sortAppend(21);
list myList3;
myList3 = myList + myList2;
return 0;
}
谁能指出我哪里出错了?我现在被困了几个小时,我不知道出了什么问题。
非常感谢!
跟进:
sortAppend 方法确实有效。它确实根据需要创建了一个排序列表。 尽管我已经尝试使用 for 循环进行一次迭代而不是范围循环,但 + 运算符定义本身肯定有问题,但我仍然只得到一个包含两个值的列表。
最佳答案
您根本没有将 inf.tail 设置为新的尾部
else if ((newElem->value) > (inf.tail->value)) {
newElem->next = nullptr;
inf.tail->next = newElem;
inf.tail = newElem; // <-- missing!
return true;
}
您至少应该更改 operator+ 的签名以返回 list
而不是列表引用,并返回本地对象而不是无主堆对象(这是内存泄漏)。如果这样做,您还必须编写复制构造函数和复制赋值运算符。
关于c++ - 列表实现没有正确地对列表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921250/