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が指している to を作成しています。そのため、ポインターのいずれかが、それが指しているリソースの割り当てを解除し、他のdanglingを残すと、問題が発生します。

nextしたがって、各インスタンスが独立して保持する場所を指すポインターを作成する必要があります。そう、 -

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

優れた説明があるこのスレッドもお読みください - Rule of Three

于 2011-05-02T01:15:36.897 に答える