[英]C++ Deep Copying Linked List
首先,这是我目前正在尝试解决的任务的一部分。 我正在尝试创建一个复制构造函数来深度复制给定的 LinkedList。 我已经对 LinkedList 方法进行了编码。
这是 LinkedList.h 文件的必要部分。
LinkedList.h
private:
struct node {
Val data;
node* next = nullptr;
};
typedef struct node* nodePtr;
nodePtr head = nullptr;
nodePtr current = nullptr;
nodePtr temp = nullptr;
};
参数给出: "LinkedList::LinkedList(const LinkedList & ll)" ll 是要复制的链表。 我首先测试链表中是否有头,如果没有,则表示链表为空。 然后我将旧列表中的头部复制到新列表中。 然后我将新电流设置到头部以准备 while 循环。 在 while 循环中,我正在复制当前节点的数据以及指向下一个节点的指针。 最后,我将下一个指针设置为 nullptr 以表示新列表的结尾。
LinkedList.cpp
LinkedList::LinkedList(const LinkedList & ll){
if (ll.head == nullptr) {
return;
}
head = ll.head;
current = head;
while (ll.current->next != nullptr) {
current->data = ll.current->data;
current->next = ll.current->next;
}
current->next = nullptr;
}
我不确定这是否是深度复制。 我也知道ll.current的起始位置不在头部。 我试过 ll.current = ll.head。 然而,由于给出了这个函数是const。 我不能这样设置。
还有另一个函数: LinkedList & LinkedList::operator=(const LinkedList & ll) { } 我怀疑可能需要。 我希望我可以选择使用它。
您需要在添加新内存或新列表元素时分配它们,更改代码以执行以下操作:
// LinkedList.cpp
LinkedList::LinkedList(const LinkedList & ll)
{
if (ll.head == nullptr)
return;
// Create a temp variable since ll.current doesn't move/change.
node* tmp = ll.head;
// Allocate a new node in memory.
head = new node;
// Copy over the value.
head->data = tmp->data;
// Set the 'next' value to null (the loop will fill this in).
head->next = nullptr;
// Point 'current' to 'head'.
current = head;
// Move to next item in ll's list.
tmp = tmp->next;
while (tmp != nullptr)
{
// Allocate new memory for a new 'node'.
current->next = new node;
// Point to this new 'node'.
current = current->next;
// Copy over the data.
current->data = tmp->data;
// By default set the 'next' to null.
current->next = nullptr;
// Move along ll's list.
tmp = tmp->next;
}
}
此外,在你的班级中去掉typedef node* nodePtr
。 没有必要,只需将node*
用于head
、 current
和temp
干净了。 最后,不要忘记在类的析构函数中清除动态分配的内存:
LinkedList::~LinkedList()
{
current = head;
while(current != nullptr)
{
current = current->next;
delete head;
head = current;
}
}
这是行不通的,因为您永远不会为实际的列表对象分配新的列表元素(使用“new”运算符),而只会重用现有的元素。 试想一下,如果 ll 的元素比实际列表多,会发生什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.