2011-05-02 219 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