复制简单单链接列表的构造函数,包括节点C ++

时间:2011-05-02 01:05:31

标签: c++ copy-constructor singly-linked-list

我不是很擅长这个,我有点卡住为单个链表制作复制构造函数以及随之而来的节点。

这是我的头文件:

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

有谁能帮我理解这是如何运作的,以及我可以做些什么来创造它?谢谢。

2 个答案:

答案 0 :(得分: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数据成员等。您必须考虑这些因素。

答案 1 :(得分: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) ;
    // ....
}  

另请阅读此主题有一个很好的解释 - Rule of Three

相关问题