2011-05-02 223 views
1

我不是很擅長這一點,而且我有點卡住爲單個鏈表和與它一起的節點製作複製構造函數。包含節點的簡單單鏈表的複製構造函數C++

這裏是我的頭文件:

#pragma once 

#include <iostream> 
using namespace std; 

class Node 
{ 
public: 
    int data; 
    Node* next; 
    Node() 
    { 
     next = NULL; 
     data = 0; 
    } 
    Node(const Node& copyNode); /*: data(copyNode.data), next(copyNode.next ? new Node(*copyNode.next) : NULL)*/ 

}; 

class SLLIntStorage 
{ 
public: 
    Node* head; 
    Node* current; 
    Node* tail; 

    void Read(istream&); 
    void Write(ostream&); 
    void setReadSort(bool); 
    void sortOwn(); 
    void print(); 

    void mergeSort(Node**); 
    Node *merge(Node*, Node*); 
    void split(Node*, Node**, Node**); 

    bool _sortRead; 
    int numberOfInts; 

    SLLIntStorage(const SLLIntStorage& copying) //: head(copying.head ? new Node(*copying.head) : NULL) 
    { 

    } 

    SLLIntStorage(void); 
    ~SLLIntStorage(void); 
}; 

inline ostream& operator<< (ostream& out, SLLIntStorage& n) 
{ 
    n.Write(out); 
    return out; 
} 
inline istream& operator>> (istream& in, SLLIntStorage& s) 
{ 
    s.Read(in); 
    return in; 
} 

誰能給我一隻手搭在瞭解如何工作的,我可以做些什麼來創造呢?謝謝。

+1

對於你可能想'更有用列表節點(INT d){未來= NULL; data = d;}',對嗎? – YXD 2011-05-02 01:19:12

+0

@Mr默認的構造函數? – 2011-05-02 12:54:27

+0

不,對於採用一個參數的構造函數,Node的數據。 – 2011-05-05 12:05:28

回答

4

要複製鏈接列表,您必須迭代整個鏈接列表並複製每個節點,並將其附加到新列表中。請記住,您不僅要複製指針,還必須複製整個Node結構以及任何需要複製的數據(例如,如果數據是指針,則需要對這些指針進行深層複製)。

因此,這裏是你的SLLIntStorage類的例子拷貝構造函數:

SLLIntStorage(const SLLIntStorage& copying) : head(NULL) 
{ 
    Node* cur = copying.head; 
    Node* end = NULL; 

    while (cur) 
    { 
     Node* n = new Node; 
     n->data = cur->data; 

     if (!head) { 
      head = n; 
      end = head; 
     } else { 
      end->next = n; 
      end = n; 
     } 

     cur = cur->next; 
    } 
} 

請注意,我並沒有考慮到tailcurrent數據成員,等等。你必須考慮到這些。

+0

對不起,但即時通訊有點簡單,我瞭解你的代碼,但我想知道如果你可以擴大請嗎?林不知道你得到什麼,而不是你的錯,我的大腦和我開始大聲笑 – 2011-05-02 11:18:30

+1

@Tanya圖像鏈接列表對象。它只是一個指向鏈表開始的指針。要製作該鏈接列表的副本**,以便修改其中一個不會修改另一個**,則必須轉到鏈接列表的每個項目,併爲該項目創建_new副本,並將其添加到新項目你正在製作的鏈表。 – 2011-05-02 19:10:05

1

因爲這是作業,我會嘗試給出一個想法,從中你可以找出你需要做的複製構造函數。

Node(const Node& copyNode) : data(copyNode.data), 
          next(copyNode.next) 
{ 
    // .... 
} 

在上面的代碼中你只是在實際進行nextcopyNode::next所指向的位置。所以,當任何一個指針釋放其指向的其他資源時,你會遇到問題,而其他懸掛

所以,你應該使指針next每個實例指向它獨立擁有的位置。所以, -

Node(const Node& copyNode) : data(copyNode.data), 
          next(new Node) 
{ 
    (*next) = *(copyNode.next) ; 
    // .... 
} 

還可以閱讀此線程具有優異的解釋 - Rule of Three