t3h*_*iel 4 c++ struct 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;
};
Run Code Online (Sandbox Code Playgroud)
参数给出: "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;
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是否是深度复制。我也知道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;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,在你的课堂上摆脱typedef node* nodePtr. 有没有必要的,它的清洁,以简单地使用node*了head,current和temp。最后,不要忘记在类的析构函数中清除动态分配的内存:
LinkedList::~LinkedList()
{
current = head;
while(current != nullptr)
{
current = current->next;
delete head;
head = current;
}
}
Run Code Online (Sandbox Code Playgroud)