我正在尝试创建一个单独链接列表类的深层复制构造函数。它复制了新列表的头部,并将元素附加到该列表的末尾(通过调用附录)函数。
完整代码可在此处提供:https://onlinegdb.com/hke0ev8bg
有人可以指出我要出错的地方吗?非常感谢!
class LinkedList
{
class Node
{
public:
int *data;
Node *next;
Node() {
data = NULL;
next = NULL;
}
Node(int *d) {
data = d;
next = NULL;
}
};
private:
Node *head;
int itemCount;
public:
LinkedList() {
head = NULL;
itemCount = 0;
}
//COPY CONSTRUCTOR
LinkedList(LinkedList ©)
{
Node *temp = copy.head;
while (temp != NULL)
{
append(temp->data);
temp = temp->next;
}
}
//ADD TO THE END OF A LIST
void append(int *d) {
Node *tail = new Node;
tail->data = d;
tail->next = NULL;
if (head == NULL) {
head = tail;
}
else {
Node *temp = new Node;
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = tail;
}
itemCount++;
}
问题在于该程序在复制构造函数部分陷入"分段故障"。
您忘了在复制构造器中初始化LinkedList::head
和LinkedList::itemCount
。仅当实际使用常规构造函数时,在常规构造函数中执行的初始化。
结果,LinkedList::append
在检查head
指针时会看到随机垃圾,假定其有效,然后在使用该无效指针时会导致SEG故障。