对链表复制构造函数和赋值运算符使用copy()方法
问题描述:
我想实现链接列表的复制构造函数。我已经写了返回的将是用于拷贝构造函数和重载赋值运算符列表的复制方法:对链表复制构造函数和赋值运算符使用copy()方法
template<class T>
SinglyList<T> SinglyList<T>::copy(Node *u) {
SinglyList<T> newList;
Node *current = u;
if (current->next==NULL) {
newList.add(current->x);
} else while (current!=NULL) {
newList.add(current->x);
current = current->next;
}
return newList;
}
通过上面这里使用的add()方法:
template<class T>
void SinglyList<T>::add(T x) {
Node *u = new Node(x);
if (n == 0) {
head = u;
} else {
tail->next = u;
}
tail = u;
n++;
}
我一直在努力执行拷贝构造函数像这样:
template<class T>
SinglyList<T>::SinglyList(const SinglyList<T> &a) {
this->copy(a.head); //Does this not work?
}
我在运行代码本身的main():
int main() {
SinglyList<int> test;
for (int i=0; i<5; i++)
test.add(i);
test.print(); //This outputs 0 1 2 3 4
SinglyList<int> test2 = test;
test2.print(); //This should output 0 1 2 3 4 but outputs a bunch of garbage numbers
return 0;
}
然后它崩溃。我不完全确定问题是什么。它是与复制构造函数还是复制方法?
关于重载赋值运算符,使用复制方法不起作用,但在重载工作中运行代码本身?
template<class T>
SinglyList<T>& SinglyList<T>::operator=(const SinglyList<T> &b) {
//this->copy(b.head); <---This doesn't work
Node *current = b.head;
if (current->next==NULL) {
this->add(current->x);
} else while (current!=NULL) {
this->add(current->x);
current = current->next;
}
return *this;
}
伴随着类代码:
template<class T>
class SinglyList {
protected:
class Node {
public:
T x;
Node *next;
Node(T x0) {
x = x0;
next = NULL;
}
};
Node *head;
Node *tail;
int n;
SinglyList<T> copy(Node*);
public:
SinglyList();
SinglyList(const SinglyList<T>&);
~SinglyList() {
Node *u = head;
while (u != NULL) {
Node *w = u;
u = u->next;
delete w;
}
};
void add(T);
SinglyList<T>& operator=(const SinglyList<T>&);
void print();
};
免责声明:本部分的代码是从Open Data Structures解除,HW是修改代码以额外的功能添加到现有的代码。
答
有几个问题,最大的是无限递归。
您的复制构造函数调用copy
函数,该函数按值返回一个新列表,这意味着它将被复制并调用复制构造函数。等等等等。使用调试器可以轻松检测到此问题。我建议你花些时间到learn how to debug your programs。
通过正确初始化成员变量,您可以使用赋值运算符(如显示它)来实现复制构造函数,如*this = a;
。
但是,我宁愿建议您修改copy
函数,从另一个列表复制到这个列表,而不是创建一个新列表并返回它。
有关赋值运算符......你不得不考虑的情况下,当电流名单已经有节点,您必须先删除它们。