1

我不是很擅长这个,我有点坚持为单个链表和与之配套的节点制作复制构造函数。

这是我的头文件:

#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;
}

谁能帮我理解它是如何工作的以及我可以做些什么来创建它?谢谢你。

4

2 回答 2

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数据成员等。您必须考虑这些。

于 2011-05-02T01:09:57.227 回答
1

由于这是家庭作业,我将尝试给出一些想法,您可以从中找出您需要使用复制构造函数做什么。

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

在上面的代码片段中,您实际上只是在next指向该位置copyNode::next所指向的点。因此,当任何指针解除分配它指向的资源而留下另一个悬空的资源时,您就会遇到问题。

因此,您应该使next每个实例的指针指向它独立保存的位置。所以, -

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

另请阅读此线程,它有一个很好的解释 -三法则

于 2011-05-02T01:15:36.897 回答