2016-11-25 66 views
1

首先,這是我目前試圖找出的一項任務的一部分。我試圖創建一個複製給定的LinkedList的複製構造函數。 我已經編碼了LinkedList方法。C++深層複製鏈接列表

以下是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的& 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的。我不能這樣設定。

還有給出另一種功能: { } 鏈表&鏈表::運算符=(const的鏈表& LL),我懷疑可能是必要的。我希望我可以選擇使用它。

+0

首先寫複製構造函數和析構函數。一旦你實現這些功能,賦值運算符就很簡單。另外,如果'll.head'是'nullptr',你的拷貝構造函數會立即錯誤。原因是你沒有初始化任何成員 - 你只是'返回'。 – PaulMcKenzie

+3

這不是深層複製。深度複製涉及在複製值之前爲成員分配內存。 – sameerkn

+0

此外,您目前正在重寫'current-> data'和'current-> next'中的值,而不會更改'current'指向的位置。 –

回答

1

您需要分配新的內存或新的列表元素,你將它們添加,更改代碼執行以下操作:

// 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->value = tmp->value; 
    // 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,currenttemp。最後,不要忘記在你的班級的破壞者清除動態分配內存:

LinkedList::~LinkedList() 
{ 
    current = head; 

    while(current != nullptr) 
    { 
     current = current->next; 
     delete head; 
     head = current; 
    } 
} 
+0

您是否看過我的評論?如果'll.head'是'nullptr',則複製構造函數會立即出錯,因爲成員變量未初始化。您應該首先在成員初始化列表中初始化所有指針。 'LinkedList :: LinkedList(const LinkedList&ll):head(nullptr),current(nullptr){...}' – PaulMcKenzie

+0

'll.head'被檢查是否爲空。在'.h'文件中,他已經將'head','current'和'temp'設置爲'nullptr',並初始化它們。我錯過了什麼嗎?在C++ 11中,您可以在頭文件中初始化OP寫入的方式。 – user2205930

1

這是行不通的,因爲您從不爲實際列表對象分配新的列表元素(使用'new'運算符),但僅重用現有列表元素。想想會發生什麼,如果ll比實際列表中有更多元素?

+0

謝謝, 我已經改變它,現在它的工作。 – t3hdaniel