[英]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.